mongoid验证has_many或has_and_belongs_to_many关系中每个成员的唯一性

时间:2014-11-24 22:09:42

标签: ruby-on-rails validation ruby-on-rails-4 mongoid mongoid4

我有一个类似于以下内容的模型

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

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

这完全可以很好地验证讲师每个组织的每个时间表是唯一的......

当我尝试制作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

如何解决这个问题,以便评估has_many的唯一性,就像评估has_one关系一样

我希望得到类似以下的内容

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

我看过this answer但它无法正常工作

1 个答案:

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

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