Ruby on Rails Thursday, August 8, 2013

Savater Sebastien wrote in post #1118021:
> class Parent < ActiveRecord::Base
> has_many :items
> end
>
> class Item < ActiveRecord::Base
> belongs_to :parent
> end
>
> I need to delete all items associated to one parent, without callback.
> I don't need to call #destroy, but only executing the appropriate SQL
> statement.
>
> First case :
>
>> parent.items.delete_all
> ...
> So.. What's the proper way ?

If I understand correctly your intent is to delete all "items"
associated to "parent" but not delete the "parent" itself. If that
assumption is correct you don't have to use the association at all. Just
delete what you want directly from the Item model as follows:

Item.delete_all([ "parent_id = ?", parent.id ])
or
Item.where([ "parent_id = ?", parent.id ]).delete_all

I would also recommend using the :dependent option on your association.
It makes no sense for "items" to exist without their owning "parent"
object. In other words, parent "owns" its items.

class Parent < ActiveRecord::Base
has_many :items, :dependent => :destroy
end

This way you won't orphan items if a parent were to be destroyed.

--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/8832a2015910a5e3d4c7aaacfd0fec49%40ruby-forum.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment