【问题标题】:MongoID many to many relation shipMongoDB多对多关系
【发布时间】:2013-01-02 02:12:24
【问题描述】:

我有两个具有以下关系的模型,

Class User
has_and_belongs_to_many :notification_channels

Class NotificationChannel
has_and_belongs_to_many :users

我可以通过这种方式为用户对象添加通知通道

@user.notification_channels << @notification

但是从用户的频道中删除频道将使用以下查询从频道集合中删除频道文档

@user.notification_channels.find_by(id: params[:channel_id]).destroy 

如何从用户的频道中删除频道?

【问题讨论】:

    标签: ruby-on-rails-3 mongodb mongoid mongoid3


    【解决方案1】:

    解决办法

     @user.notification_channels -= [NotificationChannel.find_by(id: params[:channel_id])] # relationship is removed both ways and both objects are saved
    

    或

     @user.notification_channels.delete(NotificationChannel.find_by(id: params[:channel_id])) # relationship is removed both ways but @user needs to be saved manually
     @user.save
    

    会成功的。

    【讨论】:

      猜你喜欢
      • 2018-11-03
      • 1970-01-01
      • 2014-01-21
      • 2014-08-15
      • 2020-12-05
      • 1970-01-01
      • 2014-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多