create table foo (id, name, order, ...);
create table foo_bar (id, foo_id, name, value);
foo contains order column with values as (1,2,3,4,5,...10) assuming foo_bar contains multiple records for each foo.
How do I delete foos whose order values are 3..6 and its dependent records?
class Foo < ActiveRecord::Base
has_many :foo_bars, :dependent => :destroy
end
class FooBar < ActiveRecord::Base
belongs_to :foo
end
If your relation is like above following code will work
Foo.delete_all(["id in (?)", [3,4,5,6]])
OR Just
Foo.delete([3,4,5,6])
Ref delete
EDITED
From little i know your question i think you have something like 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 user following order
instead of id
Foo.delete_all(["order in (?)", [3,4,5,6]])
The correct answer, to destroy(delete) the dependens:
As @Salil said if your model has the dependent callback
like this:
has_many :foo_bars, :dependent => :destroy
Your query to destroy the parent and dependent records should be:
Foo.where(order: [1, 2, 3, 4]).destroy_all
The method where
will get all records with the array of orders
and call the destroy
method for each record found.
JUST USE delete
or delete_all
if you don't want to execute the callbacks about destroy dependencies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With