SeattleDucati
SeattleDucati

Reputation: 293

Rails 4 - Displaying values from different model in a view

I have a model, Ownerships. Ownerships belongs_to another model called Team. Team has_many Ownerships. Ownerships is indexed off 'team_id' from the Team table in the db.

One of the columns in the Ownerships db table is 'team_id'. In the index view for ownerships, I want to be able to display the name of the team from the :name column in the Team table, based on the team_id. I've been hacking at it for hours with no success.

Ownerships controller:

class OwnershipsController < ApplicationController
  def index
    @ownerships = Ownership.all
    @team = Team.all
  end
  def show
    @ownership = Ownership.find(params[:id])
  end
end

The pertinent part of my index.html.erb view for ownerships:

<% @ownerships.each do |ownership| %>
  <tr>
    <td><%= ownership.round %></td>
    <td><%= ownership.pick %></td>       
    <td><%= ownership.team.team_id { |a| a.name } %></td> 
    #want to display team name above
  </tr>
<% end %>

Any help would be appreciated.

Upvotes: 1

Views: 1719

Answers (3)

divergent
divergent

Reputation: 291

One of the columns in the Ownerships db table is 'team_id'.

In that case you can simply go:

<% @ownerships.each do |ownership| %> <%= ownership.team.name %> <% end %>

Upvotes: 1

David Aldridge
David Aldridge

Reputation: 52356

Since you have many ownerships in the view, invoke eager loading on the team association, and then reference the team name.

<% @ownerships.eager_load(:team).each do |ownership| %>
  <tr>
    <td><%= ownership.round %></td>
    <td><%= ownership.pick %></td>
    <td><%= ownership.team.name %></td> 
   </tr>
   <% end %>

The eager loading will make the page more efficient by left joining from the ownership to the team, and no further queries will be required to get the team name for each ownership.

If it's possible for there to be an ownership without a team, use:

        <td><%= ownership.team.try(:name) %></td> 

Upvotes: 2

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34338

Just use:

<td><%= ownership.team.name%></td> 

as you already have association setup between ownership and team models.

Upvotes: 4

Related Questions