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 curr开发者_如何学JAVAent_user
(I'm using devise, so current_user
is a valid User
object).
current_user.score_cards << score_card
OR
score_card.user = current_user
score_card.save
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.
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
精彩评论