Reputation: 41442
Let's say you have a one-to-many relationship between Users and Orders (where one user can have many orders). Is it possible to create a User object, add orders to it, and save it in one go? Or do you have to save the User object first so that an ID is generated before you can save the orders collection?
Upvotes: 2
Views: 98
Reputation: 41442
I was able to solve this by using the "build" method. From the ActiveRecord::Associations::ClassMethods documentation:
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.
Upvotes: 0
Reputation: 5041
Since the User
is a new record, orders
will be saved automatically once the user
is saved.
Upvotes: 1
Reputation: 1752
You can check Railscasts for that. Here's an example of a nested model - Nested Model Form Part 1
Upvotes: 5