开发者

Rails ActiveRecord associations

开发者 https://www.devze.com 2023-02-28 06:49 出处:网络
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 yo

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号