user1491929
user1491929

Reputation: 664

Activerecord: Remove multiple associations via array

I have a has_many through:

Foo has many Bar through foo_bars

I want to pass an array of bar ids to some method on Foo that will remove the relationship in both directions-

Something like

foo.bars.delete([1,3,5,8])

However, delete only accepts the ID of one Model. There has got to be a way to do this in bulk and I just cannot find the answer. Any help is much appreciated.

Upvotes: 4

Views: 1978

Answers (2)

GEkk
GEkk

Reputation: 1366

Unfortunately Richard Peck code will not work if want to delete an array of ids.
You will get a "some association expected, got Fixnum" error.
This code will be able to do the job:

foo.bars.where(id: array_of_ids).delete_all

But the best way I found this to work is based on this answer comments and related to Richard answer is to use splat = * :

foo.bars.delete(*array_of_ids)

Upvotes: 3

Richard Peck
Richard Peck

Reputation: 76784

Interesting question - I originally thought you'll probably be looking for delete_all or destroy_all, but after doing some testing & looking at the Rails docs, it said you can only use delete


After testing, I found by calling delete_all you could get rid of all the collection data (foo.bars.delete_all):

enter image description here


I then tested using a naked delete method foo.bars.delete(x,y). This worked - :

enter image description here

So the answer is:

foo.bars.delete(1,2,3,4)

Upvotes: 1

Related Questions