Search code examples
ruby-on-railsrubyruby-on-rails-3model-associations

Ruby on Rails: How to display everything associated with user?


I have some associations that is connected to the user

User model

has_many :lists
has_many :ideas

How do I display the lists and ideas in the user's page?

In my users controller, show method

  def show
  @user = User.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @user } 
    end  
  end

In my show.html.erb

I can only display user name, i.e.:

<%= @user.username %>

I'm trying to see what I need to put in the show action so I can do something like

@user.lists.name, or @user.ideas.name

I'm new to rails still and I'm trying to understand how to link everything together with user?

Hopefully this is enough information?

Thanks


Solution

  • Those associations returns collections, an array of many objects. So you must iterate though all the association records.

    <p>Name: <%= @user.username %></p>
    
    <p>Ideas:</p>
    <ul>
      <% @user.ideas.each do |idea| %>
        <li><%= idea.name %></li>
      <% end %>
    </ul>
    
    <p>Lists:</p>
    <ul>
      <% @user.lists.each do |list| %>
        <li><%= list.name %></li>
      <% end %>
    </ul>
    

    Which might render something like:

    <p>Name: Andrew</p>
    
    <p>Ideas:</p>
    <ul>
      <li>Light Bulb</li>
      <li>Cotton Gin</li>
      <li>Smokeless Ashtray</li>
    </ul>
    
    <p>Lists:</p>
    <ul>
      <li>Chores</li>
      <li>Shopping</li>
      <li>Wishlist</li>
    </ul>