How to delete multiple records with dependent records in ActiveRecord

create table foo (id, name, order, ...); create table foo_bar (id, foo_id, name, value); 

foo contains an order column with values ​​like (1,2,3,4,5, ... 10) assuming foo_bar contains several entries for each foo.

How to remove foos with ordinal values ​​3..6 and dependent records?

+4
source share
2 answers
 class Foo < ActiveRecord::Base has_many :foo_bars, :dependent => :destroy end class FooBar < ActiveRecord::Base belongs_to :foo end 

If your attitude is similar above, the following code will work

 Foo.delete_all(["id in (?)", [3,4,5,6]]) 

Or simply

 Foo.delete([3,4,5,6]) 

Ref remove

edited

From little I know your question, I think you have something like the following

foo table

 id some_column order 1 some_value 3 2 some_value 4 3 some_value 3 4 some_value 2 5 some_value 1 6 some_value 5 7 some_value 6 

Foo_bar table

 id some_column foo_id 1 some_value 2 2 some_value 1 3 some_value 3 4 some_value 2 5 some_value 4 6 some_value 5 7 some_value 6 

Then the user following order instead of id

 Foo.delete_all(["order in (?)", [3,4,5,6]]) 
+12
source

The correct answer is to destroy (remove) dependencies:

As @Salil said, if your model has a dependent callback like this:

 has_many :foo_bars, :dependent => :destroy 

Your request to destroy parent and dependent records should be:

 Foo.where(order: [1, 2, 3, 4]).destroy_all 

The where method will get all the records with the orders array and call the destroy method for each record found.

USE ONLY delete or delete_all if you do not want to make callbacks about the destroyed dependencies.

0
source

Source: https://habr.com/ru/post/1395545/


All Articles