Ruby on Rails: Create a new record that belongs to another model -
i have users
, have posts
.
i want create new post user #1. want using syntax similar option #2, chained original user selection. possible?
option 1 (i know how this):
user = user.find(1) post = post.create(content: "foobar content", user: user)
option 2 (is possible?):
user.find(1).new_post(content: "foobar content")
use build
method:
user = user.find(1).posts.build(content: "post content")
in case of has_one
relationship, invoke build_association
method:
user = user.find(1).build_profile(content: "profile content")
in either event, new child object initialized , associated parent user
, however, you'll need save
user
instance in order preserve association:
user.save
alternatively, same associations can created via create
, create_association
methods:
user.find(1).posts.create(content: "post content") user.find(1).create_profile(content: "profile content")
neither call requires parent saved – associated child created , saved @ instant respective creation method called.
an important note: both create
, create_association
methods deprecated in rails 4.
Comments
Post a Comment