验证属性和has_many通过关系

时间:2013-11-12 17:20:49

标签: ruby-on-rails validation has-many-through validates-uniqueness-of

我有以下结构:

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,其中:该基金过滤器的名称不会重复。

想法?

1 个答案:

答案 0 :(得分: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