Rails:更新模型属性而不调用回调 [英] Rails: Update model attribute without invoking callbacks
问题描述
我有一个具有 :credits 属性的 User 模型.我想要一个简单的按钮,通过名为add"的路由为用户的信用添加 5,以便/users/3/add 将向用户 id = 3 的信用添加 5.
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
end
那是我的控制器的相关部分.问题是,我不想调用 @user.save 因为我有一个 before_save 回调,它根据当前的 UTC 时间重新加密用户的密码.只想简单的给属性加5,避免回调,没想到这么简单的事情这么难.
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.
我将回调更改为:before_create,这是我的新控制器代码(相关部分):
I changed the callback to :before_create, here is my new controller code (relevant part):
def add
@user = User.find(params[:id])
@user.add_credits(5)
@user.save
flash[:success] = "Credits added!"
redirect_to root_path
end
这是我在模型中的代码:
and here is my code in the model:
def add_credits(num)
self.credits = num
end
编辑 2:
好吧,这是一个验证问题,导致EDIT"中的更改不起作用,但我仍然希望回答不带回调的原始更新问题!
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 引入了 update_column
,与 update_attribute
相同,但不触发验证或回调:
Rails 3.1 introduced update_column
, which is the same as update_attribute
, but without triggering validations or callbacks:
http://apidock.com/rails/ActiveRecord/Persistence/update_column
这篇关于Rails:更新模型属性而不调用回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!