I’m new with ruby and rails and have been struggling with this issue for a few days. I know I had another association like this elsewhere in my app, but this one just isn’t working.
I have a has_many and belongs_to relationship between my Game model and Character model.
game.rb
has_many :characters
character.rb
belongs_to :game, :foreign_key => 'game_id'
I want to be able to store the game_id in the character and then show the game’s name in the view like this:
<%= @character.game.name %>
But I get this error:
NoMethodError in Characters#show
Showing …/rpglegion/app/views/characters/show.html.erb where line #5 raised:
undefined method `name’ for nil:NilClass
Extracted source (around line #5):
5: <%= @character.game.name %>
Application Trace | Framework Trace | Full Trace
app/views/characters/show.html.erb:5:in >_app_views_characters_show_html_erb___872566584_80495980′
app/controllers/characters_controller.rb:20:in `show’
_characters_controller.rb_
def show
@character = Character.find(params[:id])
respond_to do |format| #line 20
format.html # show.html.erb
format.xml { render :xml => @character }
end
end
I can’t figure out what exactly I’m doing wrong that the associations aren’t working. Can somebody please help me?
First, “game_id” is implied by the belongs_to association, so you can remove the :foreign_key part.
Second, does the @character actually have a game_id set to a game? If not, open a console, find the character you’re looking at, and set it’s game_id to an existing game. For instance: