I knew I can do that (last example, I made a bad copy/paste of arguments :))

Item.where(parent: parent.id).delete_all 



But I hoped we can use associations, which offering a better *readability*.
In Rails 3, you can simply make :

parent.items.delete_all



Otherwise, I already use :dependent option (with :delete_all, in my case).
As, It's not the point here, I tried to keep my example simple.


Le jeudi 8 août 2013 15:12:51 UTC+2, Ruby-Forum.com User a écrit :
>
> 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+unsubscr...@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/ee9abe82-d253-471e-8454-97944e22f7bb%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to