验证范围为 :through 关联的字段的唯一性

Validate uniqueness of a field scoped with :through association

有 3 个型号:TalkTopicConference。 每个都有一个标题和一个描述。 一个Conference有很多Topics,一个Topic有很多谈话。

class Conference < ApplicationRecord
    has_many :topics
    has_many :talks, through: topics
end

class Topic < ApplicationRecord
    belongs_to :conference
    has_many :talks
end

class Talk < ApplicationRecord
    belongs_to :topic
    belongs_to :conference, through: :topic
end

如何验证 TalkConference 中具有唯一标题?

我能想到的唯一解决方案是为 Talk-Topic 关联创建另一个 table 并在那里执行验证。但是如果不创建一个新的 table?

可以实现吗?

试试这个

validate :unique_talk_in_conference
def unique_talk_in_conference
   if self.conference.talks.collect(&:title).include?(self.title)
       errors.add(:title, "Talks should be unique in a conference")
   end
end

P.S: 没测试过