gpt4 book ai didi

ruby-on-rails - rails : Update model attribute without invoking callbacks

转载 作者:数据小太阳 更新时间:2023-10-29 06:19:46 25 4
gpt4 key购买 nike

我有一个具有 :credits 属性的用户模型。我想要一个简单的按钮,它将通过名为“add”的路由将 5 添加到用户的积分中,以便/users/3/add 将 5 添加到用户 id = 3 的积分中。

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

那是我 Controller 的相关部分。问题是,我不想调用@user.save,因为我有一个before_save 回调,它根据当前的UTC 时间重新加密用户的密码。我只想简单的给属性加5,避免回调,没想到这么简单的事情这么难。

编辑:

我将回调更改为:before_create,这是我的新 Controller 代码(相关部分):

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

这是我在模型中的代码:

 def add_credits(num)
self.credits = num
end

编辑 2:

好吧,这是一个验证问题,导致“EDIT”中的更改不起作用,但我仍然喜欢在没有回调的情况下更新原始问题的答案!

最佳答案

Rails 3.1 引入了update_column,与update_attribute 相同,但不触发验证或回调:

http://apidock.com/rails/ActiveRecord/Persistence/update_column

关于ruby-on-rails - rails : Update model attribute without invoking callbacks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8650983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com