1

i have the following structure:

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

What i need is a validator on the :name of a fund_filter, which cannot repeat for a single user. Meaning for a single user_id in FundFilterUser, i need to check all fund_filter_ids where :name for that fund filter doesnt get repeated.

Ideas?

saGii
  • 447
  • 5
  • 14

1 Answers1

0

It's possible to implement a custom validator that checks for duplicate names in fund_filters associated to the user.

It may looks like this:

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
evedovelli
  • 2,115
  • 28
  • 28