Reputation: 464
Up until Rails 4.1 it was possible to start a transaction, create two records and reference them before committing changes into the DB.
Records are in the many-to-many relationship with existence constraint on both ends, i.e. there cannot be an empty group nor can a person not belong to at least one group.
Class outlines:
class Person
has_and_belongs_to_many :groups
validates_presence_of :groups
end
class Group
has_and_belongs_to_many :persons
validates_presence_of :persons
end
Transaction code example:
Person.transaction do
person = Person.new(...)
group = Group.create!(..., persons: [person])
person.groups << group
person.save!
end
Is there a way to defer the existence check till the commit phase? Any better suggestion?
Upvotes: 0
Views: 51
Reputation: 3048
Just use inverse_of
. That should solve your problem:
class Person
has_and_belongs_to_many :groups, inverse_of: :groups
...
end
class Group
has_and_belongs_to_many :persons, inverse_of: :persons
..
end
Upvotes: 1