这是Rails 4.1.4中的3个示例类。 B
可以被视为has_and_belongs_to_many
中产阶级(但事实并非如此):
class A < AR::Base
has_many :bs
accepts_nested_attributes_for :bs
end
class B < AR::Base
belongs_to :c
belongs_to :a
accepts_nested_attributes_for :c
end
class C < AR::Base
has_many :bs
end
这个结构允许我创建这样的objets:
a = A.create!({
:attr_a => 'valA',
:b_attributes => {
0 => {
:attr_b => 'valB0',
:c_attributes => { :attr_c => 'valC' }
},
1 => {
:attr_b => 'valB1',
:c_attributes => { :attr_c => 'valC' }
}
}
})
它完美地工作,我有一个对象A,2个对象B和2个对象C.
问题在于我想添加一个C的attr_c 的单一性。所以我在C
模型中添加了这一行:
validates :attr_c, :uniqueness => true
但是......对于Rails没有问题,C
的 2个实例已创建,名称完全相同。我指出当我想创建C
&#34;手动&#34;的2个实例时(没有nested_attributes),它会引发正确的错误。
有什么方法可以:
或
c
自动设置相同的b
个实例?