1

I have two models with following relations,

Class User
has_and_belongs_to_many :notification_channels

Class NotificationChannel
has_and_belongs_to_many :users

I am able to add notification channel for a user object in this way

@user.notification_channels << @notification

But removing channel from user's channels will remove the channel document from channels collection with following query

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

how can I remove a channel from user's channel ?

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
Umair Ejaz
  • 273
  • 1
  • 2
  • 15

1 Answers1

0

Here is the solution

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

OR

 @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

Will do the trick.

abhas
  • 5,193
  • 1
  • 32
  • 56