Ruby on rails 在rails中,如何通过关联在一个has-many上拥有唯一的约束

Ruby on rails 在rails中,如何通过关联在一个has-many上拥有唯一的约束,ruby-on-rails,validation,activerecord,has-many-through,Ruby On Rails,Validation,Activerecord,Has Many Through,我有以下资料: class A < Active... has_many :bs has_many :cs, through: :bs accepts_nested_attributes_for :bs accepts_nested_attributes_for :cs end clas B < Active... belongs_to :a belongs_to :b accepts_nested_attributes_for :cs end clas

我有以下资料:

class A < Active... 
  has_many :bs
  has_many :cs, through: :bs
  accepts_nested_attributes_for :bs
  accepts_nested_attributes_for :cs
end
clas B < Active...
  belongs_to :a
  belongs_to :b
  accepts_nested_attributes_for :cs
end
class C < Active... 
  has_many :bs
  has_many :as, through: :bs
end
然后,在删除或更新第一个A之前,不能为其他A分配['c1','c2']

我可以想出两种方法,但有没有一种方法:

1) 对
A
表进行非规范化,添加一个“cs”列,该列包含与每个
A
对象关联的所有
cs
字符串,然后对该新的“cs”列施加约束

2) 将所有现有的
实例化为
,并将每个实例与新的
a

最大的问题是同时为As
a=a使用嵌套的_属性创建
As
Cs
(Bs_属性:[{Cs_属性:{…},{Cs_属性:{…}])
将不会填充
a.cs
,直到它创建了
a
,此时进行回调验证已经太晚了。

在B中,您可以

validates :c_id, :uniqueness => { :scope => :a_id }

您的建议只确保没有C与A关联一次以上。first.cs.pullc(:key)=>['c1','c1']将无效。我将更新该问题,以明确验证应在任何A关联的cs集上进行。谢谢:)
validates :c_id, :uniqueness => { :scope => :a_id }