ruby on rails - Validate uniqueness of a field scoped with :through association -
there 3 models: talk, topic , conference. each have title , description. conference has many topics , topic has many talks.
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 how validate talk has unique title within conference?
the solution come create table talk-topic association , perform validation there. can achieved without creating new table?
try this
validate :unique_talk_in_conference def unique_talk_in_conference if self.conference.talks.collect(&:title).include?(self.title) errors.add(:title, "talks should unique in conference") end end p.s: didn't test it
Comments
Post a Comment