before_destroy in rails, little help need!
i have table called users
, if i want to delete some user
(User can add questions
and ad开发者_如何转开发d respondents
(who will answer
on his questions
)), i need to delete him and get his id to people who deleted this person. So for example:
Sure.
def destroy_and_transfer_to(user)
transaction do
questions.each do |q|
q.update_attribute(:user_id => user)
end
respondents.each do |r|
r.update_attribute(:user_id => user)
end
destroy
end
end
Now use this method instead of the "destroy" method. OR you can stick to callbacks like this
before_destroy :transfer_to
attr_accessor :user_who_takes_over
private
def transfer_to
if user_who_takes_over
questions.each do |q|
q.update_attribute(:user_id => user_who_takes_over)
end
respondents.each do |r|
r.update_attribute(:user_id => user_who_takes_over)
end
end
end
Then you can :
@user.user_who_takes_over = current_user
@user.destroy
Just a couple of ideas! Good Luck!
Update: All the code i provided above belongs in your model. In your controller you need to have a destroy method
in your controller
def destroy
user = User.find(params[:id])
user.user_who_takes_over = current_user
if user.destroy
flash[:notice] = "User destroyed, all stuff transferred"
else
Rails.logger.debug(user.errors.inspect)
flash[:error] = "Error destroying user"
end
redirect_to :back
end
Change to suite your need of course!
精彩评论