1

在此示例中,我想将Thingsa的数量限制Person为 5:

class Person < ActiveRecord::Base
  has_many :things

  def things_limit_reached?
    self.things.count >= 5
  end
end

并在返回 trueThing时将错误添加到新的: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

我错过了什么?

4

1 回答 1

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
于 2012-08-19T19:57:13.550 回答