1

次の関係を持つ2つのモデルがあります。

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 に答える