我使用Rails 3.2.11的Mac OS X山獅,紅寶石1.9.3before_validation在軌失敗
所以我有這樣一段代碼:
class Points < ActiveRecord::Base
validates :id, :presence => true
before_create :validate_points
def validate_points
if self.amount < 0
Rails.logger.error "Invalid amount of points"
else
save!
end
end
末
我想限制用戶插入負值。但由於某種原因,validate_points方法不起作用。我做錯了什麼?謝謝。
這是不正確的。 'before_create'只會觸發一次。如果是'before_save',那麼我會同意你的看法。 – jvnill 2013-03-07 07:32:55
當您保存一個new_record時,before_create將被遞歸調用,因爲它沒有機會成爲一個「現有記錄」。 這就是爲什麼它會在before_create的死循環中。 – rxing 2013-03-07 07:48:35
嗯有趣。現在我更多地思考它,你是對的。它永遠不會超過創造記錄的地步。很好的接收! – jvnill 2013-03-07 07:50:43