oka*_*56k 3 ruby-on-rails infinite-loop ruby-on-rails-3
好吧,这件事让我抓狂.我有一个看起来像这样的小方法:
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
Run Code Online (Sandbox Code Playgroud)
而我的error方法只会导致stack level too deep错误.有人可以帮我理解为什么吗?根据我的逻辑,它应该工作得很好.谢谢.我需要防止error_code以某种方式改变吗?
update_attributes保存模型,触发回调.你不应该save在before_save回调中触发,或者是的,你将耗尽堆栈.
而不是这个:
update_attributes(press_ready_url: nil, low_resolution_url: nil)
Run Code Online (Sandbox Code Playgroud)
用这个:
self.press_ready_url = self.low_resolution_url = nil
Run Code Online (Sandbox Code Playgroud)