【问题标题】:mongoid validate uniqueness of each member in has_many or has_and_belongs_to_many relationmongoid 验证 has_many 或 has_and_belongs_to_many 关系中每个成员的唯一性
【发布时间】:2014-11-24 22:09:41
【问题描述】:

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

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,但没有成功

【问题讨论】:

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


    【解决方案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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-30
      • 2019-09-17
      • 1970-01-01
      相关资源
      最近更新 更多