艺术家Group_by嵌套属性Order_date
我创建了一个运作良好的电子商务平台,会员可以在这里购买歌曲。 一切正常,但我想按月分组我的所有订单。
目前,我可以将每个专辑与其相应的艺术家和每个有序歌曲分组到相应的专辑。 但现在我想按月分组订单。
如何通过订单表中的order_date对艺术家进行分组,以便所有内容按月组织?
Ex. of what I've like to do Month 1 Orders Artist1 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 Orders Artist2 Album1 --Song2 (1 Order) Artist3 Album3 --Song5 (1 Order)
楷模
class Order < ActiveRecord::Base attr_accessible :artist_id, :album_id, :song_id, :user_id, :order_date belongs_to :song belongs_to :user end class Artist :albums has_many :orders, :through => :songs end class Album :songs end class Song < ActiveRecord::Base attr_accessible :artist_id, :album_id, :title, :price belongs_to :album has_many :orders end
CONTROLLERS
###How Can I Group Artists by the order_date in my Orders Table? def index @artists = Artist.includes(:orders).where('orders.id IS NOT NULL') end
VIEWS
###Lists All Artists with Orders ###Lists All Albums corresponding to Artist ###Lists All Ordered Songs corresponding to Albums = 1 %> () $
您可以通过以下行获得订单列表:
<% @order_months.sort.each do |month, orders| %>
但是你会跳回到你的完整艺术家名单中:
<% @artists.each do |artist| %> ###Lists All Artists with Orders
相反,我认为你需要类似的东西
<% orders.each do |order| %> <% order.artists.each do |artist| %> <% artist.albums.each do |album| %> <% album.songs.each do |song| %> <%= song.name %>
要获得order.artists,您需要修改您的模型:
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
这就是我最终解决问题的方法
调节器
@orders = Order.find(:all, :order => 'order_date, id', :limit => 50)
查看
<% @orders.sort.group_by { |order| order.order_date.beginning_of_month }.each do |month, orders| %> <%= month.strftime('%B') %>
<% orders.group_by { |order| order.song.album.artist }.each do |artist, orders| %> <%= artist.name %>
<% orders.group_by { |order| order.song.album }.each do |album, orders| %> <%= album.name %>
<% orders.group_by { |order| order.song }.each do |song, orders| %> (<%= orders.count %>) <%= song.title %>
<%= song.price %>
<% end %> <% end %> <% end %> <% end %>