41

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).

ryanprayogo
  • 11,587
  • 11
  • 51
  • 66

3 Answers3

71
current_user.score_cards << score_card

OR

score_card.user = current_user
score_card.save
grzuy
  • 4,791
  • 2
  • 20
  • 17
13

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.

Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261
11

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

Abram
  • 39,950
  • 26
  • 134
  • 184