嗨,我在模型中使用 has_and_belongs_to_many。
我想为种类设置存在的 valitor。
并将每个核心的最大种类数设置为 3
class Core < ActiveRecord::Base
has_and_belongs_to_many :kinds, :foreign_key => 'core_id', :association_foreign_key => 'kind_id'
end
我能怎么做?
谢谢
最佳答案
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
关于ruby-on-rails - 验证 has_and_belongs_to_many 的存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2158188/