简体   繁体   中英

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. 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

bar2 = Bar.create(name: "bar2")

now we have two bar objects

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". 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"

I'm not sure exactly what association you want it on since all those foobars are hard to parse. 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

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. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM