hatboysam hatboysam - 6 months ago 13
Ruby Question

Rails: Update model attribute without invoking callbacks

I have a User model that has a :credits attribute. I want a simple button that will add 5 to the user's credits, through a route called "add" so that /users/3/add would add 5 to the credits of user id = 3.

def add
@user = User.find(params[:id])
@user.credits += 5
redirect_to root_path

That is the relevant part of my controller. The problem is, I dont want to call @user.save because I have a before_save callback that re-encrypts the user's password based on the current UTC time. I just want to simply add 5 to the attribute and avoid the callback, I never thought such a simple thing could be so hard.


I changed the callback to :before_create,
here is my new controller code (relevant part):

def add
@user = User.find(params[:id])
flash[:success] = "Credits added!"
redirect_to root_path

and here is my code in the model:

def add_credits(num)
self.credits = num


Ok it was a validation problem that made the changes in "EDIT" not work, but I'd still love an answer to the original question of updating without callbacks!


Rails 3.1 introduced update_column, which is the same as update_attribute, but without triggering validations or callbacks: