1

次のようなモデルがあります

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

この回答を見ましたが、うまくいきませんでした

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 に答える