【发布时间】:2017-11-09 20:25:15
【问题描述】:
有问题的 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
但该验证似乎没有影响。
对我在这里做错了什么有任何见解吗?
【问题讨论】:
-
那为什么不能使用
has_one而不是has_many? -
为什么不在您的
Child模型上使用has_one :relationship和has_one :outage, :through => :relationship? Rails Guide 描述了这种关联。 -
@TomAranda 对,我就是这么想的。试过了,但这仍然允许孩子与不同的中断相关联。
-
您可能想要添加一个唯一索引,如链接指南中所述。
-
@TomAranda 您的意思是为
child_id创建一个唯一索引,对吗?t.index ["child_id"], name: "index_relationships_on_child_id", unique: true
标签: ruby-on-rails activerecord model-associations