Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding object to associated collection without yet saving

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.

like image 227
Peter Stackov Avatar asked Oct 15 '12 18:10

Peter Stackov


1 Answers

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
like image 121
messanjah Avatar answered Nov 17 '22 23:11

messanjah