2016-11-10 69 views
0

有3种型号:TalkTopicConference。 每个人都有一个标题和一个描述。 A Conference有很多TopicsTopic有很多谈话。验证独特性与作用域:通过关联

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关联创建另一个表并在其中执行验证。但是,这可以在不创建新表的情况下实现吗?

回答

0

试试这个

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:我没有测试它