1

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

4

1 回答 1

1

我能想出的唯一解决方案是以下

  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

我不认为这是最好的解决方案......所以如果有人有更好的解决方案,请添加它......

于 2014-11-25T01:21:05.900 回答