ruby-on-rails - 堆栈级别太深且 before_save

标签 ruby-on-rails ruby-on-rails-3 infinite-loop

好吧,这件事快把我逼疯了。我有一个看起来大致像这样的小方法:

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 错误。有人可以帮我理解为什么吗?按照我的逻辑,它应该工作得很好。谢谢。我是否需要防止 error_code 以某种方式更改?

最佳答案

update_attributes 保存模型,触发回调。您不应该在 before_save 回调中触发 save,否则,您会耗尽堆栈。

取而代之的是:

update_attributes(press_ready_url: nil, low_resolution_url: nil)

使用这个:

self.press_ready_url = self.low_resolution_url = nil

关于ruby-on-rails - 堆栈级别太深且 before_save,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27179606/

相关文章:

ruby-on-rails - Ruby & Rails - 使用 CSV 中的关联播种数据

ruby-on-rails - AWS Elasticbeanstalk 应用程序的 Rails : How to get puma 3. 11?

javascript - 在 Rails 中添加 Javascript

recursion - 超出堆栈限制 (0.2Gb)...可能无限递归(循环):

while循环中的Javascript continue语句导致无限循环

c - 为什么这段代码永远循环?

ruby-on-rails - 使用 bundle install 安装 bcrypt 时出错

ruby-on-rails - Ruby on Rails "content_for :title"如何获得稍后分配的内容?

ruby-on-rails - 从 Controller 发送。需要帮忙

ruby-on-rails - CanCan之间的区别:read and [:index, :show]?