我有以下结构:
class FundFilter < ActiveRecord::Base
has_many :fund_filter_users, dependent: :destroy
has_many :users, through: :fund_filter_users
end
class FundFilterUser < ActiveRecord::Base
belongs_to :fund_filter
belongs_to :user
end
class User < ActiveRecord::Base
has_many :fund_filter_users, dependent: :destroy
has_many :fund_filters, through: :fund_filter_users
end
我需要的是一个fund_filter 的 :name 上的验证器,它不能为单个用户重复。对于FundFilterUser中的单个user_id的含义,我需要检查该基金过滤器的:name不重复的所有fund_filter_ids。
想法?
可以实现一个自定义验证器,用于检查与用户关联的fund_filters中的重复名称。
它可能看起来像这样:
class User < ActiveRecord::Base
has_many :fund_filter_users, dependent: :destroy
has_many :fund_filters, through: :fund_filter_users
validate :fund_filters, has_uniq_name
def has_uniq_name
all_fund_filter_from_user = []
fund_filter_users.each do |fund_filter_user|
all_fund_filter_from_user = all_fund_filter_from_user.concat(fund_filter_user.fund_filters)
end
errors.add(:fund_filters, "cannot have repeated names") unless all_fund_filter_from_user.collect{|p| p.name}.uniq.length == all_fund_filter_from_user.length
end
end