3

I have users, who have posts.

I want to create a new post for user #1. I want to do this using syntax similar to Option #2, where its chained to the original user selection. Is this possible?

Option 1 (I know how to do this):

user = User.find(1)
post = Post.create(content: "foobar content", user: user)

Option 2 (is this possible?):

User.find(1).new_post(content: "foobar content") 
1

1 Answer 1

3

Use the build method:

user = User.find(1).posts.build(content: "post content")

In the case of a has_one relationship, invoke the build_association method:

user = User.find(1).build_profile(content: "profile content")

In either event, a new child object is initialized and associated to the parent User, however, you'll need to save your User instance in order to preserve the association:

user.save

Alternatively, the same associations can be created via the create and create_association methods:

User.find(1).posts.create(content: "post content")
User.find(1).create_profile(content: "profile content")

Neither call requires that the parent be saved – the associated child is created and saved at the instant that the respective creation method is called.

An important note: both the create and create_association methods are deprecated in Rails 4.

Sign up to request clarification or add additional context in comments.

6 Comments

Also it could be creation instead of initializing. I guess he should know that this should be saved.
Awesome thanks guys. Will accept when timer is up. Also maybe you have insight into this question: stackoverflow.com/questions/23944676/…
@zishe, creation methods are deprecated in Rails 4, but I've updated my answer to reflect.
@DonnyP, no need to cross-post. If someone has an answer to your other questions, they'll post. If this answer has helped resolve your issue, please consider upvoting/accepting it as correct.
@zeantsoi thanks, didn't know about that, guides.rubyonrails has no info about that, while it's deprecated since 3.1 version.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.