1

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

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 

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

4

1 回答 1

0

这是解决方案

 @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

会成功的。

于 2013-01-18T13:49:15.510 回答