验证has_and_belongs_to_many的存在

Luc*_*oli 5 ruby-on-rails has-and-belongs-to-many

嗨,我在模型中使用has_and_belongs_to_many.我想设置各种存在的价值.并将每个核心的最大种类数设置为3

class Core < ActiveRecord::Base
  has_and_belongs_to_many :kinds, :foreign_key => 'core_id', :association_foreign_key => 'kind_id'
end
Run Code Online (Sandbox Code Playgroud)

我能怎么做?

谢谢

Ale*_*ner 6

validate :require_at_least_one_kind
validate :limit_to_three_kinds

private

def require_at_least_one_kind
  if kinds.count == 0
    errors.add_to_base "Please select at least one kind"
  end
end

def limit_to_three_kinds
  if kinds.count > 3
    errors.add_to_base "No more than 3 kinds, please"
  end
end
Run Code Online (Sandbox Code Playgroud)