Artists Group_by nested attribute Order_date

社会主义新天地 提交于 2019-12-04 22:52:21

You get the list of orders ok with this line:

<% @order_months.sort.each do |month, orders| %>

But then you jump back into your full list of artists with this line:

   <% @artists.each do |artist| %>             ###Lists All Artists with Orders

Instead I think you need something like

   <% orders.each do |order| %>
     <% order.artists.each do |artist| %>
       <% artist.albums.each do |album| %> 
         <% album.songs.each do |song| %>
             <%= song.name %>

To get order.artists you will need to modify your model:

class Order < ActiveRecord::Base
  attr_accessible :artist_id, :album_id, :song_id, :user_id, :order_date

  belongs_to :song
  belongs_to :user

  has_many :albums, through: :song
  has_many :artists, through: :albums

end

This is how I ended up Solving the Problem

Controller

@orders = Order.find(:all, :order => 'order_date, id', :limit => 50)

Views

<% @orders.sort.group_by { |order| order.order_date.beginning_of_month }.each do |month, orders| %>
  <h3><%= month.strftime('%B') %> </h3>

  <% orders.group_by { |order| order.song.album.artist }.each do |artist, orders| %>
    <h4><%= artist.name %> </h4>

    <% orders.group_by { |order| order.song.album }.each do |album, orders| %>
      <h5><%= album.name %> </h5>

        <% orders.group_by { |order| order.song }.each do |song, orders| %>
          <p>(<%= orders.count %>) <%= song.title %> </p>
          <p><%= song.price %> </p>
        <% end %>

    <% end %>

  <% end %>

<% end %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!