Search code examples
ruby-on-railsruby-on-rails-3has-manybelongs-to

Rails - Show which client a project belongs to in the project index view


A client has_many projects. A project belongs_to a client.

How do I show in the index view, inside the @projects loop, which client that project belongs to?

This is what I'm trying to do in the view:

<% @projects.each do |project| %>
   <% project.client.name %>
<% end %>

Here's all I have in the projects controller & I think this is where I'm stuck:

  def index
    @projects = Project.all
    @project = Project.new
    @clients = Client.select("DISTINCT name, id")

    respond_to do |format|
      format.html # index.html.erb
      format.json { render :json => @projects }
    end
  end

I got this working with a HABTM relationship, but I'm trying to do it w/ a has_many belongs_to relationship now instead.


Solution

  • Replace this

    <% @projects.each do |project| %>
       <% project.client.name %>
    <% end %>
    

    with

    <% @projects.each do |project| %>
       <%= project.client.name %>
    <% end %>