在此示例中,我想将Things
Person
的数量限制为5:
class Person < ActiveRecord::Base
has_many :things
def things_limit_reached?
self.things.count >= 5
end
end
并在Thing
返回true时向新person.things_limit_reached?
添加错误:
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
我错过了什么?
答案 0 :(得分:0)
它应该像这样工作(未经测试):
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