Forum: Ruby on Rails destroy on has_many relationships.

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Josh K. (Guest)
on 2006-06-07 16:24
i need to delete a record from the database and delete all of it's
children as well. is there a method for this? right now, i am finding
all the children with the parent_id and destroying them first and then
destroying the parent. seems like there would be a better way to do this
but i can't seem to figure it out.

thanks,
josh
Josh K. (Guest)
on 2006-06-07 19:43
> i need to delete a record from the database and delete all of it's
> children as well. is there a method for this? right now, i am finding
> all the children with the parent_id and destroying them first and then
> destroying the parent. seems like there would be a better way to do this
> but i can't seem to figure it out.
>

ok, i think i figured it out. in the model i put something like

has_many :whatevers, :dependent => :destroy

now when i delete the parent model, it destroy's all the children as
well. if there is a better way, please let me know.
Alex W. (Guest)
on 2006-06-07 20:48
Josh K. wrote:
>> i need to delete a record from the database and delete all of it's
>> children as well. is there a method for this? right now, i am finding
>> all the children with the parent_id and destroying them first and then
>> destroying the parent. seems like there would be a better way to do this
>> but i can't seem to figure it out.
>>
>
> ok, i think i figured it out. in the model i put something like
>
> has_many :whatevers, :dependent => :destroy
>
> now when i delete the parent model, it destroy's all the children as
> well. if there is a better way, please let me know.

That is the preferred method.
This topic is locked and can not be replied to.