Rails 3.2.7:验证模型不超过数量限制(仅在创建时)

时间:2012-08-19 19:40:03

标签: ruby-on-rails

在此示例中,我想将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

我错过了什么?

1 个答案:

答案 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