[英]Rails 3.2.7: Validate model does not exceed quantity limit (on create only)
在此示例中,我想將一個Person
可以擁有的Things
數量限制為5:
class Person < ActiveRecord::Base
has_many :things
def things_limit_reached?
self.things.count >= 5
end
end
並在person.things_limit_reached?
時向新的Thing
添加錯誤person.things_limit_reached?
返回true:
class Thing < ActiveRecord::Base
belongs_to :person
validate :limit_check, :on => :create
def limit_check
errors.add :base, 'Things limit reached.' if person.things_limit_reached?
end
end
可悲的是,每當我嘗試保存現有的Thing
,即使尚未達到限制,上述代碼也會引發以下異常:
SystemStackError (stack level too deep):
actionpack (3.2.7) lib/action_dispatch/middleware/reloader.rb:70
我想念什么?
它應該像這樣(未經測試)工作:
class Thing < ActiveRecord::Base
belongs_to :person
before_create :limit_check
def limit_check
if person.things_limit_reached?
errors.add :base, 'Things limit reached.'
return false
end
return true
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.