1

我有以下结构:

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的名称上的验证器,它不能为单个用户重复。FundFilterUser 中单个 user_id 的含义,我需要检查所有fund_filter_ids,其中:该基金过滤器的名称不会重复。

想法?

4

1 回答 1

0

可以实现一个自定义验证器来检查与用户关联的 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
于 2014-05-20T14:00:15.930 回答