我使用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