首页 文章

堆栈级别太深和before_save

提问于
浏览
2

好吧,这件事让我抓狂 . 我有一个看起来像这样的小方法:

class PdfResult < ActiveRecord::Base
  attr_accessible :press_ready_url, :low_resolution_url, :error_code,
                  :document_id

  before_save :update_values

  def created?
    return true if press_ready_url.present? && low_resolution_url.present?
  end

  def error?
    error_code == 201 || error_code == 204 ? false : true
  end

  private

  def update_values
    return if error?
    self.updated_at = Time.now
    if created?
      self.error_code = 201
    else
      update_attributes(press_ready_url: nil, low_resolution_url: nil)
      self.error_code = 204
    end
    save!
  end
end

而我的 error 方法只会导致 stack level too deep 错误 . 有人可以帮我理解为什么吗?根据我的逻辑,它应该工作得很好 . 谢谢 . 我需要以某种方式防范_2900246改变吗?

1 回答

  • 6

    update_attributes 保存模型,触发回调 . 你不应该在 before_save 回调中触发 save ,或者是的,你将耗尽堆栈 .

    而不是这个:

    update_attributes(press_ready_url: nil, low_resolution_url: nil)
    

    用这个:

    self.press_ready_url = self.low_resolution_url = nil
    

相关问题