如何限制轨道中的模型?

时间:2014-04-10 20:07:43

标签: ruby-on-rails

我有一个模型通话组。

我想添加一个阻止超过8组的验证

请帮帮我

class Group < ActiveRecord::Base
    validates :name, :presence => true
    validates :name, :uniqueness => true
    validates :name, :length => { :is => 1 }
    validates :name, :format => { :with => /\A[A-Z]+\z/, :message => "Grupo Invalido" }
end

1 个答案:

答案 0 :(得分:1)

试试这个:

class Group < ActiveRecord::Base
    validates :name, :presence => true
    validates :name, :uniqueness => true
    validates :name, :length => { :is => 1 }
    validates :name, :format => { :with => /\A[A-Z]+\z/, :message => "Grupo Invalido" }
    validate :max_count, on: :create

    def max_count
      errors.add(:base, 'Max group count limit reached') if Group.count >= 8
    end
end