【问题标题】:Rails ActiveRecord callbacks dilemmaRails ActiveRecord 回调困境
【发布时间】:2015-08-20 02:28:03
【问题描述】:

如果存在重复项,我正在尝试更新 rails 记录,如下所示:

class Rating < ActiveRecord::Base
  before_create :update_rating_if_already_exists

  def update_rating_if_already_exists
    original_rating = Rating.where(user: self.user, article: self.article)
    if original_rating.blank?
      true
    else
      original_rating[0].update_attribute(:score, self.score)
      false
    end
  end
end

但是问题是,当我如上所述使用after_create 时,这对于控制器操作的正常使用将不起作用,因为控制器将首先使用给定的参数构建类的新实例,然后save(不是create) 新对象。

但是,如果我将上面的内容更改为after_save,它会解决控制器问题,但会导致另一个问题:

original_rating[0].update_attribute(:score, self.score)

将尝试使用save 方法更新原始记录,该方法还将触发before_save...然后继续...,这会导致SystemStackError: stack level too deep 错误。

这是现在的两难境地,我的问题是我该如何解决这个问题?

感谢所有贡献。 :)

【问题讨论】:

    标签: ruby-on-rails activerecord callback


    【解决方案1】:

    您可以将before_savenew_record? 条件一起使用,以避免在update_attribute 调用上执行回调。

    before_save :update_rating_if_already_exists, if: :new_record?
    
    def update_rating_if_already_exists
      # method code
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-04
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多