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
最大的问题是同时为Asa=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 }