从帐户访问项目列表

时间:2014-07-01 07:44:55

标签: ruby-on-rails ruby-on-rails-4

以下是给出我的帐户列表的代码。

<% @accounts.each do |account| %>
  <li><%= link_to account.name %></li>
<% end %>  

如何访问我的特定帐户的项目列表。

1 个答案:

答案 0 :(得分:2)

试试这个:

<% @accounts.each do |account| %>
  <li><%= link_to account.name %></li>
  <li><%= link_to account.projects %></li>  #this will give you a collection of projects associated with that account
<% end %> 

如果你想为每个项目提供link_to,那么你将不得不使用另一个循环:

<% @accounts.each do |account| %>
  <li><%= link_to account.name %></li>
  <% account.projects.each do |project| %>
    <li><%= link_to project %></li>  #this will give you individual project associated with that account
  <% end %>
<% end %> 

编辑:

如果您没有任何帐户项目,您可以这样做:

<% @accounts.each do |account| %>
  <li><%= link_to account.name %></li>
  <% if account.projects %>
    <% account.projects.each do |project| %>
      <li><%= link_to project %></li>  #this will give you individual project associated with that account
    <% end %>
  <% else %>  # add this else block to execute your code when there are on projects 
    <p> No projects associated with your account</p>
  <% end %>
<% end %>
相关问题