ryanprayogo
ryanprayogo

Reputation: 11817

Rails association - how to add the 'has_many' object to the 'owner'

In my app, a user has many score_cards and a score_card belongs to a user

The question is, whenever I create a new score_card, ie, ScoreCardsController.create gets called, how do I add this newly created score_card to the current_user (I'm using devise, so current_user is a valid User object).

Upvotes: 41

Views: 33252

Answers (3)

grzuy
grzuy

Reputation: 5041

current_user.score_cards << score_card

OR

score_card.user = current_user
score_card.save

Upvotes: 72

Abram
Abram

Reputation: 41914

I'm going to throw this out there in case anyone is looking for a way to add multiple objects to an associated object:

score_cards = ScoreCard.all
current_user.score_cards << score_cards

No need to current_user.save

Upvotes: 11

Ryan Bigg
Ryan Bigg

Reputation: 107728

Use the association builder method:

current_user.score_cards.build(params[:score_card])

Alternatively to build you can use create or create! if you don't care about the validations in the controller.

Upvotes: 13

Related Questions