Suppose I have a pair of models:
class Club < ActiveRecord:Base
has_many :members, autosave: true
end
class Member < ActiveRecord:Base
belongs_to :club
end
I would like to be able to add some new members to a club, without yet persisting the new members, until I save the club. How could I do this?
Using <<
to add a member to a club does not work as I want, since this automatically saves the member.
According to the has_many documentation, the "shovel" method collection<<(object, …)
Adds one or more objects to the collection by setting their foreign keys to the collection's primary key. Note that this operation instantly fires update SQL without waiting for the save or update call on the parent object, unless the parent object is a new record.
If you want to construct a new-record without saving it to the database just yet, use collection.build
.
Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved.
Using Club and Member as example models:
club = Club.find(params[:id])
club.members.build(member_attributes) # member is not saved
club.save # saves club and members
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With