按月/艺术家组织并添加歌曲价格

时间:2014-05-26 02:09:42

标签: ruby ruby-on-rails-3 group-by e-commerce nested-loops

我创建了一个运作良好的电子商务平台,会员可以在这里购买歌曲。一切正常,但我想在我的索引页面中显示艺术家每个月产生的总收入。

目前我可以按月分组。艺术家,但我正在努力创建一种方法,增加所有的歌曲价格,以产生艺术家的总收入。

如何添加艺术家的有序歌曲价格以为该艺术家生成该月的总收入?

EX. of what I'd like:

Month 1 
  Artist1 ($Total Artist Revenue Month 1)  
    Album1                    ###List of Albums Corresponding to an Artist 
    --Song1 (10 0rders)          
    --Song3 (5 Orders)
    Album2 
    --Song5 (2 Orders)        ###Ordered Songs Corresponding to an Album 

Month 2  
  Artist2  ($Total Artist Revenue Month 2)
    Album1 
    --Song2 (1 Order)
  Artist3  ($Total Artist Revenue Month 2)
    Album3 
    --Song5 (1 Order)

模型

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

  belongs_to :song
  belongs_to :user

end

class Artist < ActiveRecord::Base
  attr_accessible :name

  has_many :albums
  has_many :songs, :through => :albums
  has_many :orders, :through => :songs

end

class Album < ActiveRecord::Base
  attr_accessible :name, :artist_id

  belongs_to :artist
  has_many :songs
  has_many :orders, :through => :songs

end

class Song < ActiveRecord::Base
  attr_accessible :artist_id, :album_id, :title, :price

  belongs_to :album
  has_many :orders

end

控制器

def index    
  ###Groups things by Month
  @orders = Order.find(:all, :order => 'order_date, id', :limit => 50)
end

视图

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

  <% orders.group_by { |order| order.song.album.artist.name }.each do |artist, orders| %>
    <h4><%= artist %> </h4>    ###Groups all Artist with Orders

    ###I can display the price for each song....But
    ###How Can I Add These Values or place them into a New Array 
    ###So I can generate the total revenue? 
    <% orders.each do |order| %>      
      <%= order.song.price %>    
    <% end %>   

  <% end %>

<% end %>

1 个答案:

答案 0 :(得分:1)

您可以在视图中汇总订单的价格:

<% orders.each do |order| %>
  <%= order.song.price %>
<% end %>
<%= orders.map { |o| o.song.price }.sum %>

然后您可以将该逻辑移到Artist模型中:

class Artist
  # ...
  def total_revenue(orders)
    orders.map { |o| o.song.price }.sum
  end
  # ...
end

total_revenue在某个时间范围内对所有订单求和可能更有意义,在这种情况下,ActiveRecord可以处理计算订单收入的逻辑,类似于:

class Artist
  # ...
  def total_revenue(start_interval, end_interval = start_interval.end_of_month)
    songs.joins(:orders)
         .where(orders: { order_date: start_interval..end_interval })
         .sum(:price)
  end
  # ...
end

有关使用ActiveRecord对列进行求和的详细信息,请参阅this