Topic: delete a user andl their many posts that have many children?

hi,
is there a rails way to do this? if i were to brute force this, i would probably do something like this algorithm

@user = User.find(:first, id == params[id])

@posts = Post.Find(:all, ....user_id = @user.id)

@posts.each do |f|
   Children_of_posts.destroy :conditions post_id == f.id
end

Post.destroy all where user_id = @user.id

User.destroy @user.id

Re: delete a user andl their many posts that have many children?

If you *always* want to delete a user's posts when the user is deleted you can just put it in the association:

has_many :posts, :dependent => :destroy

alternatively, a nicer way to write your code is

@user = User.destroy(params[:id])
#@user stays in memory even though it's been deleted from the database, so we can still use it
@user.posts.each{|post| post.destroy}

although i don't know what's going on with the whole Children_of_posts thing.

Last edited by Max Williams (2008-08-01 12:17:20)

###########################################
#If i've helped you then please recommend me at Working With Rails:
#http://www.workingwithrails.com/person/ … i-williams

Re: delete a user andl their many posts that have many children?

Max is correct, using :dependent on the association is the best way to do this.

If, for some reason, you cannot, you can make that just a little shorter still:

@user = User.destroy(params[:id])
@user.posts.each(&:destroy)

Re: delete a user andl their many posts that have many children?

I've used the :dependent => :destroy and it worked perfect. Thanks a lot!