Reputation: 51797
I have a model Foo and a model Bar, both of which has_many :bar_foos (and then has_many each other :through => :bar_foos). It's a simple many:many relationship between Foo and Bar, through a BarsFoo model.
I want to delete several rows in the bar_foos table. Specifically, I want to delete any bar_foo record that relates to any of a given set of Foos and any of a given set of Bars. For performance, I'd like to issue a single database call to do this.
The corresponding SQL statement would be:
DELETE FROM bar_foos WHERE bar_id IN ( ?, ?, ? ) AND foo_id in ( ?, ?, ? )
...while replacing the ?
s with the appropriate IDs.
How do I perform this using Rails 2.3.x?
Ideally, I'd to not write the actual SQL myself, but make ActiveRecord method calls instead. However, I doubt this exists.
Barring that, I'll craft the SQL statement myself, but:
Upvotes: 1
Views: 1197
Reputation: 47542
I think it's not possible using assosciation you have to write it your own (Use destroy_all)
BarFoo.destroy_all(["bar_id IN (?) AND foo_id in (?)", bar_id_array, foo_id_array])
Upvotes: 4
Reputation: 2180
You can do this...
has_many :bar_foos, :dependent => destroy
And that will destroy all the bar_foos that belong to the object that was just destroyed.
Upvotes: 0