Issue with controller calling delete_all using callbacks in Ruby on Rails (20 jan 13)
I can't remember where this code came from (maybe Authlogic?) but it has a flaw:
users_controller.rb:
def destroy
@user = User.find(params[:id])
if @user.admin?
@user.errors.add( :email, ' - admin user cannot be deleted' )
else
User.delete_all("id = " + @user.id.to_s) # wrong
respond_to do |format|
format.html { redirect_to(:users, :notice => 'Deleted') }
format.json { head :no_content }
end
end
end
user.rb:
before_destroy :reassign_media
def reassign_media
admin = User.admin! # this is the administrator
raise "I am the administrator! I can never be destroyed!" if self == admin
media.each { |m| admin.media << m unless admin.media.include?( m ) }
end
When the administrator clicks on the 'delete user' button, before deleting that user, all the 'media' objects which have that user's id as their user_id should be reassigned to the administrator. But User.delete_all doesn't call this callback.
@user.destroy does, so I replaced User.delete_all with @user.destroy.