[英]Do not create object if old object with same attribute is associated to same current object's associated table
I've has_many: :through association with tables Foo, FooBar and Bar.我有 has_many: : 通过与 Foo、FooBar 和 Bar 表的关联。 Here is their implementation:这是他们的实现:
Class Foo < ApplicationRecord
has_many :foo_bars, dependent: :destroy
has_many :bars, through: :foo_bars
end
Class FooBar < ApplicationRecord
belongs_to :foo
belongs_to :bar
end
Class Bar < ApplicationRecord
has_many :foo_bars, dependent: :destroy
has_many :foos, through: :foo_bars
end
Example:例子:
bar = Bar.create(name: "bar")
bar.foos << Foo.create(name: "foo")
foo.bars has bar object with name "bar"
bar.foos has foo object with name "foo"
and和
FooBar.first object has foo_id: 1, bar_id: 1
Let's create a new Bar object让我们创建一个新的 Bar object
bar2 = Bar.create(name: "bar2")
now we have two bar objects现在我们有两个 bar 对象
What I want to do is, I do not want to create a new foo object if foo.name = "foo" and it is being associated with bar with name "bar" because bar has already foo with "foo".我想要做的是,我不想创建一个新的 foo object 如果 foo.name = "foo" 并且它与名为 "bar" 的 bar 相关联,因为 bar 已经具有 "foo" 的 foo。 But I want to create foo object if foo.name = "foo" and it is being associated with bar2 object because bar2.foos does not have foo with name "foo"但是我想创建 foo object 如果 foo.name = "foo" 并且它与 bar2 object 相关联,因为 bar2.foos 没有名为“foo”的 foo
I'm not sure exactly what association you want it on since all those foobars are hard to parse.我不确定你到底想要什么关联,因为所有这些 foobar 都很难解析。 But it sounds like you want to validate uniqueness based on a scope which can be done by adding the following line to the model you want to be unique但听起来您想基于 scope 验证唯一性,这可以通过将以下行添加到您想要唯一的 model 来完成
validates_uniqueness_of :name, scope: :parent_id
To create a database constraint to prevent possible violations of a uniqueness validation using the:scope option, you must create a unique index on both columns in your database.要使用:scope 选项创建数据库约束以防止可能违反唯一性验证,您必须在数据库中的两个列上创建唯一索引。 Depending on what database you are using, you'll want to check either the MySQL manual for more details about multiple column indexes or the PostgreSQL manual for examples of unique constraints that refer to a group of columns (also sourced from the rails guide on validating uniqueness).根据您使用的数据库,您需要查看MySQL 手册以获取有关多列索引的更多详细信息,或者查看 PostgreSQL 手册以获取引用一组列的唯一约束示例(也来自 rails guide on validate唯一性)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.