Rails ActiveRecord 回调困境
Rails ActiveRecord callbacks dilemma
如果存在重复项,我正在尝试更新 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
时,这对于控制器操作的正常使用将不起作用,因为控制器将首先使用给定的 class 构建一个新实例params 然后 save
(不是 create
)新对象。
但是,如果我将上面的内容更改为 after_save
,它会解决控制器问题,但会导致另一个问题:
original_rating[0].update_attribute(:score, self.score)
将尝试使用 save
方法更新原始记录,这也会触发 before_save
...等等,然后...这会导致 SystemStackError: stack level too deep
错误。
这是现在的困境,我的问题是我该如何解决这个问题?
感谢所有贡献。 :)
您可以将 before_save
与 new_record?
条件一起使用,以避免在 update_attribute
调用时执行回调。
before_save :update_rating_if_already_exists, if: :new_record?
def update_rating_if_already_exists
# method code
end
如果存在重复项,我正在尝试更新 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
时,这对于控制器操作的正常使用将不起作用,因为控制器将首先使用给定的 class 构建一个新实例params 然后 save
(不是 create
)新对象。
但是,如果我将上面的内容更改为 after_save
,它会解决控制器问题,但会导致另一个问题:
original_rating[0].update_attribute(:score, self.score)
将尝试使用 save
方法更新原始记录,这也会触发 before_save
...等等,然后...这会导致 SystemStackError: stack level too deep
错误。
这是现在的困境,我的问题是我该如何解决这个问题?
感谢所有贡献。 :)
您可以将 before_save
与 new_record?
条件一起使用,以避免在 update_attribute
调用时执行回调。
before_save :update_rating_if_already_exists, if: :new_record?
def update_rating_if_already_exists
# method code
end