before_destroy in rails, little help need! -
i have table called users
, if want delete user
(user can add questions
, add respondents
(who answer
on questions
)), need delete him , id people deleted person. example:
sure.
def destroy_and_transfer_to(user) transaction questions.each |q| q.update_attribute(:user_id => user) end respondents.each |r| r.update_attribute(:user_id => user) end destroy end end
now use method instead of "destroy" method. or can stick callbacks this
before_destroy :transfer_to attr_accessor :user_who_takes_over private def transfer_to if user_who_takes_over questions.each |q| q.update_attribute(:user_id => user_who_takes_over) end respondents.each |r| r.update_attribute(:user_id => user_who_takes_over) end end end
then can :
@user.user_who_takes_over = current_user @user.destroy
just couple of ideas! luck!
update: code provided above belongs in model. in controller need have destroy method
in controller
def destroy user = user.find(params[:id]) user.user_who_takes_over = current_user if user.destroy flash[:notice] = "user destroyed, stuff transferred" else rails.logger.debug(user.errors.inspect) flash[:error] = "error destroying user" end redirect_to :back end
change suite need of course!
Comments
Post a Comment