我有三个表:
class Keeper
has_many :assignments
end
class Assignment
belongs_to :keeper
belongs_to :assignment_group
end
class AssignmentsGroup
has_many :assignments
validate :uniqueness_of_keeper
end
与一个assignment_group相关联的分配必须具有一个守护者。我的问题是:鉴于所有关联的工作分配都具有相同的管理者,我如何向has_one: keeper
添加AssignmentsGroup
关联?
答案 0 :(得分:0)
很抱歉,如果我误解了您的问题,因为目前尚不清楚AssignmentGroup
和Assignment
之间应该建立什么关联,请尝试以下方法:
class Keeper
has_many :assignments
end
class Assignment
belongs_to :keeper
belongs_to :assignment_group # will need to add a reference to the assignments table
end
class AssignmentsGroup
has_many :assignments
has_many :keepers, through: assignments
validate :single_keeper
private
def single_keeper
errors.add(:base, "can only have one keeper") unless keepers.uniq.length == 1
end
end
请参见https://guides.rubyonrails.org/active_record_validations.html#custom-methods