Rails应用程序不在回调方法中保存字段

时间:2015-04-27 09:28:11

标签: ruby-on-rails ruby

更新我的User模型时,我有一个更新credit字段的回调:

class User < ActiveRecord::Base
  around_update :adjust_credit

  ...

  def adjust_credit
    ...
    yield
    ...
    puts "LEAVING: credit was #{self.credit}"

    new_credit = self.credit - User.average_active
    puts "new credit =  #{new_credit}"

    success = self.update_attribute :credit, new_credit

    puts "AFTER SAVE CREDIT: #{User.find(self.id).credit}"
    puts "Successful? #{success}"

  end
end  

出于某种原因,credit没有更新,正如控制台日志验证的那样:

#console log
LEAVING: credit was 40
new credit =  -25
AFTER SAVE CREDIT: 40
Successful? true

2 个答案:

答案 0 :(得分:2)

修改 你的问题是,如果你在“就地”修改一个属性,这意味着:如果没有给它赋一个新的值,那么Rails会认为没有什么新的东西可以保存,所以它“优化”了保存。

试试这个:

def adjust_credit
    ...
    yield #saves
    ...
    puts "LEAVING: credit was #{self.credit}"

    new_credit = self.credit - User.average_active
    puts "new credit =  #{new_credit}"

    self.credit = new_credit
    success = self.update_column(:credit, new_credit)


    puts "AFTER SAVE CREDIT: #{User.find(self.id).credit}"
    puts "Successful? #{success}"

end

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

您应首先了解around_回调的流程。 around_*回调称为围绕操作以及before_*after_*操作内部。例如:

class User
  def before_save
    puts 'before save'
  end

  def after_save
    puts 'after_save'
  end

  def around_save
    puts 'in around save'
    yield
    puts 'out around save'
  end
end

User.save
  before save
  in around save
  out around save
  after_save
=> true

有关回调的更多详情:http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

via:Pan Thomakos

答案 1 :(得分:0)

首先使用的原因是:

self.update_attribute(:credit, new_credit)
success = self.save

update_attribute已经保存了记录,self.save会让你感到困惑

success = self.update_attribute(:credit, new_credit)

我建议使用

self.update_column(:credit, new_credit)

不同的是update_column不会再次触发回调,但update_attribute将