0

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

4

1 回答 1

2

这些关联返回集合,一个包含许多对象的数组。因此,您必须遍历所有关联记录。

<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>

这可能会呈现如下内容:

<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>
于 2013-05-10T23:56:48.457 回答