3 个有问题的模型。停电,孩子,关系。
中断可能会有很多孩子。孩子属于停电。关系是中间人表。
一个子项一次只能属于一个中断(即,如果子项 123 属于中断 A,则不能将子项 123 与不同的中断相关联(
每次中断中的子项必须是唯一的。(我已经在Relationship
模型中用validates_uniqueness_of
解决了这个问题(。
class Outage < ApplicationRecord
has_many :relationships
has_many :children, :through => :relationships
end
class Child < ApplicationRecord
has_many :relationships
has_many :outages, :through => :relationships
end
class Relationship < ApplicationRecord
belongs_to :outage
belongs_to :child
validates_uniqueness_of :outage_id, :scope => :child_id
end
我尝试像这样设置一个自定义验证器(child.rb
(:
def has_one_outage
if outages.length > 1
errors.add(:base, "a child can only belong to one outage at a time")
end
end
不过,这种验证似乎没有影响。
对我在这里做错了什么有什么见解吗?
能够通过以下方式解决它:
class Outage < ApplicationRecord
has_many :relationships
has_many :children, through: :relationships
end
class Child < ApplicationRecord
has_many :relationships
has_many :outages, through: :relationships
end
class Relationship < ApplicationRecord
belongs_to :child
belongs_to :outage
validate :ensure_one_relationship
def ensure_one_relationship
if Relationship.where(child_id: self.child_id).present?
errors.add(:base, "A trouble ticket can only be associated with one outage ticket.")
end
end
end