Search code examples
ruby-on-railsvalidationruby-on-rails-4mongoidmongoid4

mongoid validate uniqueness of each member in has_many or has_and_belongs_to_many relation


I have a model that is something similar to the following

class Lecture
  include Mongoid::Document
  belongs_to :orgnization
  belongs_to :schedule
  has_one    :lecturer

  validates :lecturer, presence: true, uniqueness: { scope: [:orgnization, :schedule] }
end

this works perfectly fine validating that the lecturer is unique per schedule per orgnization...

the problem rises when I try to make the lecture has_many :lecturers

class Lecture
  include Mongoid::Document
  belongs_to :orgnization
  belongs_to :schedule
  has_many   :lecturers

  # the following validation doesn't work
  validates :lecturers, presence: true, uniqueness: { scope: [:orgnization, :schedule] }
end

how do I fix this so that it evaluates the uniqueness of the has_many the same way it evaluates the has_one relation

I'd like to have something like the following

class Lecture
  ...
  validate :lecturers_schedule
  def lecturers_schedule
    # Pseudo code
    lecturers.each do |lecturer|
      validates :lecturer, uniqueness: { scope: [:orgnization, :schedule] }
    end
  end
end

I've looked at this answer but it didn't work


Solution

  • the only solution that I could come up with is the following

      validate  :lecturers_schedule
      def lecturers_schedule
        lecturer.each do |lecturer|
          # if any of the lecturers has any lecture
          # in the same organization and in the same schedule
          # then return validation error
          if lecturer.lectures.where(organization: organization,
                                     schedule: schedule).count > 0
            self.errors[:lecturers] << "already taken"
          end
        end
      end
    

    I don't consider this to be the best solution... so If anybody has a better solution please add it...