问题描述
我有有一个用户模式:信用属性。我想要一个简单的按钮,将增加5到用户的学分,通过一个名为路线添加,使/用户/ 3 /加将增加5到用户ID的学分= 3。
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,
这是我的新的控制器code(相关部分):
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
和这里是我的code模型:
and here is my code in the model:
def add_credits(num)
self.credits = num
end
编辑2:
好吧,这是一个验证的问题,在编辑不行所做的更改,但我仍然爱一个答案,而不回调更新原来的问题!
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
这篇关于扶手:更新模型属性,而不调用回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!