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 开发者_Python百科is generated before you can save the orders collection?
You can check Railscasts for that. Here's an example of a nested model - Nested Model Form Part 1
Since the User
is a new record, orders
will be saved automatically once the user
is saved.
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.
精彩评论