Kevin Pang
Kevin Pang

Reputation: 41442

Rails ActiveRecord associations

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

Answers (3)

Kevin Pang
Kevin Pang

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

grzuy
grzuy

Reputation: 5041

Since the User is a new record, orders will be saved automatically once the user is saved.

Upvotes: 1

edthix
edthix

Reputation: 1752

You can check Railscasts for that. Here's an example of a nested model - Nested Model Form Part 1

Upvotes: 5

Related Questions