我创建了一个功能良好的电子商务平台,会员们可以在这里购买书籍。一切正常,但我想把我的所有订单按作者的索引页面分组。
目前,我能够对每个作者进行分组,但是每个现有的图书订单都会在每个作者下面列出。而不是只列出与作者对应的图书订单。
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 控制器
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 %>发布于 2014-05-24 01:38:54
为什么不相反:
型号:
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')发布于 2014-05-24 01:31:08
我想你真的很亲密。
你只需要从属于作者的订单中拿出你的书。
像这样..。
<% @author_orders.each do |author, orders| %>
<h2><%= author %> </h2>
<% orders.each do |order| %>
<h4><%= order.book %> </h4>
<% end %>
<% end %>https://stackoverflow.com/questions/23840295
复制相似问题