我创建了一个功能齐全的电子商务平台,成员(member)可以在其中购买书籍。一切正常,但我想按作者将我的所有订单分组在我的索引页中。
目前,我可以对每个作者进行分组,但是每个现有的图书订单都会在每个作者下列出。与仅列出与该作者对应的图书订单相反。
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 %>
最佳答案
为什么不改为:
型号:
class Author < ActiveRecord::Base
attr_accessible :name
has_many :books
has_many :orders, through: :books
end
Controller :
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')
关于ruby - 按作者分组图书订单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23840295/