作者的团体订单

时间:2014-05-24 01:07:07

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

我创建了一个功能强大的电子商务平台,会员可以在这里买书。一切正常,但我想通过作者将我的所有订单分组到我的索引页面。

目前,我可以对每个作者进行分组,但每个作者都会列出每个现有的图书订单。反对仅列出与该作者相对应的图书订单。

EX. of what I'd like in my Orders Page

###Orders grouped by Authors
Author1
  Book1 belongs_to Author1   ###BookOrders grouped by Author
  Book2 belongs_to Author1  
  Book3 belongs_to Author1

Author2
  Book1 belongs_to Author2
  Book2 belongs_to Author2

Author3
  Book1 belongs_to Author3

模型

class Order < ActiveRecord::Base
  attr_accessible :author_id, :book_id, :user_id, :order_date

  belongs_to :book
  belongs_to :user

end

class Book < ActiveRecord::Base
  attr_accessible : author_id, :title, :price

  belongs_to : author
  has_many :orders
end

class Author < ActiveRecord::Base
  attr_accessible :name

  has_many :books
end  

CONTROLLER

def index  

  ###How Can I combine this so it Groups Book Orders By Author  

  ###Groups Orders by Author
  @orders = Order.find(:all, :order => 'author_id, id', :limit => 50)
  @author_orders = @orders.group_by { |order| order.book.author.name }

  ###Groups Orders by Book
  @orders = Order.find(:all, :order => 'author_id, id', :limit => 50)
  @book_orders = @orders.group_by { |order| order.book.title }

end

视图

<% @author_orders.each do |author, orders| %>
  <h2><%= author %> </h2>

  <% @book_orders.each do |book, orders| %>
     <h4><%= book %> </h4>

  <% end %>

<% end %>

2 个答案:

答案 0 :(得分:2)

为什么不改为:

型号:

class Author < ActiveRecord::Base
  attr_accessible :name

  has_many :books
  has_many :orders, through: :books
end

控制器:

def index  
  @authors = Author.includes(:orders)
end

查看

<% @authors.each do |author| %>
  <h2><%= author.name %> </h2>

  <% author.orders.each do |order| %>
     <h4><%= order.book.title %> </h4>
  <% end %>

<% end %>

更新

只显示那些有订单的作者,不幸的是你需要做一些体操。此前includes也不会完全从N + 1中保存,需要进行改进。

  @authors = Author.includes(orders: :books).where('orders.id IS NOT NULL')

答案 1 :(得分:1)

我认为你真的很接近。

您只需要从属于作者的订单中获取您的图书。

喜欢这个......

<% @author_orders.each do |author, orders| %>
  <h2><%= author %> </h2>

  <% orders.each do |order| %>
     <h4><%= order.book %> </h4>

  <% end %>

<% end %>
相关问题