I have three models, team, player, and ownerships. Their relationships look like this:
team.rb
class Team < ActiveRecord::Base
has_many :ownerships
has_many :players, through: :ownerships
validates :name, presence: true
validates :division, presence: true
end
player.rb:
class Player < ActiveRecord::Base
has_one :team, through: :ownership
has_one :ownership
validates :name, presence: true
validates :position, presence: true
end
ownership.rb
class Ownership < ActiveRecord::Base
belongs_to :player
belongs_to :team
validates :round, :pick, :team_id, presence: true
end
Ownerships is indexed off both player_id and team_id:
add_index "ownerships", ["player_id"], name: "index_ownerships_on_player_id"
add_index "ownerships", ["team_id"], name: "index_ownerships_on_team_id"
When I update an ownership, the player(s) show up fine when I show the team(show.html.erb). But when I display the players index view, I get weird output from <%= player.team %>. The team assignments are working, but, the team names get displayed as things like
#<Team:0x007f8f37a76f20> and #<Team:0x007f8f37a4c360>.
I've tried <%= player.team.name %>, but that throws an undefined method error.
How can I get the team names to display correctly? And what are those values I'm seeing above?
Thank you in advance.
This the pertinent part of the players index.html.erb page:
<% @players.each do |player| %>
<tr>
<td></td>
<td><%= player.name %></td>
<td><%= player.position %></td>
<td><%= player.team %></td>
</tr>
<% end %>
EDIT:
When I user <%= player.team.name %>, I get:
undefined method `name' for nil:NilClass
The index action from the players_controller.rb is basic:
def index
@players = Player.all
end
Would the way I'm selecting the players matter? I'm using a drop down menu in the ownership edit form that looks like this:
<%= form_for @ownership do |f| %>
<p>
<%= f.label :team_id %><br>
<%= @ownership.team.name %>
</p>
<p><%= f.label :player_id %><br>
<%= f.collection_select(:player_id, Player.all, :id, :name)%>
</p>
<p>
<%= f.submit %>
</p>
<% end %>