Reputation: 453
I'm new to ruby and rails so be gentle.
i currently have 3 models (game, match, player, user)
game.rb
has_many :matches
match.rb
belongs_to :game
has_many :players
player.rb
belongs_to :match
belongs_to :user
now i want to fill those associations in the player model.
what i basically do:
players_controller.rb
def create
@game = Game.find(params[:game_id])
@match = @game.matches.find(params[:match_id])
@player = @match.players.create(params[:player])
@player.user = User.find(current_user.id)
end
after that i want to call in a view
<%= @player.user.email %>
then this error raises:
undefined method `email' for nil:NilClass
so my question is what i do wrong going backwards in associations? it should be possible somehow
Upvotes: 0
Views: 56
Reputation: 239312
You need to call @player.save
after assigning to @player.user
. Your associations are not "backwards", you simply need to save the record after updating any of its attributes to commit the changes to the database.
Currently your create method creates a new player via @match.players.create(...)
. This is the last time your player
object is written to the database. The next line, which assigns a user to the user
association, is never saved.
And a note on style: If current_player
is a player object, you should just be assigning it directly to @player.user
instead of looking up the object you already have. The last line:
@player.user = User.find(current_user.id)
Should be written:
@player.user = current_user
Upvotes: 1
Reputation: 30773
You are missing @player.save
after assigning the user attribute.
Upvotes: 0