简体   繁体   中英

Displaying has_many, :through association records

I am working on an application a deep association. A Story belongs to a Planning Level, the Planning Level belongs to one or many Programs.

class Program < ActiveRecord::Base
  has_and_belongs_to_many :planning_levels
  has_many :stories, :through => :planning_levels
end

class PlanningLevelsPrograms < ActiveRecord::Base
end

class PlanningLevel < ActiveRecord::Base
  has_and_belongs_to_many :programs
  has_many :stories
end

class Story < ActiveRecord::Base
  belongs_to :planning_level
end

Within the Program show page I'd like to display the Program, each Planning Level and aggregate Story count for each Planning Level.

I'm not sure how to access the Story model from the Program show page.

The following works great for displaying each Planning Level belonging to the Program.

<% @program.planning_levels.each do |p| %>
  <p><%= p.name %></p>
<% end %>

...but I have no idea how to make the following work for each displayed Planning Level. How do I access the Story model from with the Program? Is there something needed in the Program controller that I'm missing. Thanks in advance!

@program.planning_level.stories.count(:id)

Each Planning Level:

<% @program.planning_levels.each do |planning_level| %>
  <p><%= planning_level.name %></p>
  # Aggregate Story count for each planning_level
  <p><%= planning_level.stories.count %></p>
<% end %>

Aggregate Story count for @program (if you want):

@program.stories.count

Hope this can help you.

In your view, you can simply use the model associations by name to do this. Try this code as a starting point for your display needs:

<% @program.planning_levels.each do |planning_level| %>
  <p><%= planning_level.name %> with <%= planning_level.stories.count %> stories</p>
  <% planning_level.stories.each do |story| %>
    <p><%= story.name %></p>
  <% end %>
<% end %>

You can output any details that you choose for the stories loop. You can add styling to get the presentation that you need.

For instance, you might consider formatting this as a nested list, like so:

<% @program.planning_levels.each do |planning_level| %>
  <ul>
    <li>Planning Level: <%= planning_level.name %> with <%= planning_level.stories.count %> stories
      <ul>
        <% planning_level.stories.each do |story| %>
          <li>Story: <%= story.name %></li>
        <% end %>
      </ul>
    </li>
  </ul>
<% end %>

Adding CSS class and id attributes would give you the ability to add styling to the elements to give your UI some flair.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM