问题描述
我有一个包含 line_items 和供应商的订单模型.显示订单时,我想按供应商对 line_items 进行分组.
I have an orders model with line_items and vendors. When displaying an order, I want to group line_items by vendors.
class LineItem < ActiveRecord::Base
belongs_to :order
belongs_to :vendor
end
class Order < ActiveRecord::Base
has_many :line_items
has_many :vendors, :through => :line_items
end
class Vendor < ActiveRecord::Base
has_many :line_items
end
我想显示供应商和订单项的排序列表:
I want to display a sorted list of vendors and line items:
You have placed an order for the following items:
Vendor 1
Line item 1
Line item 2
Line item 3
Vendor 2
Line Item 4
Line Item 5
...
我现在的想法是
order.vendors.each do |a_vendor|
a_vendor.name
!!?? AND THEN WHAT GOES HERE ??!!
end
请帮忙.我想不通.也许这可以通过排序来完成?
please help. I can't figure this out. maybe this could be done by sorting?
如果订单只有一个供应商,那么我只想显示一个供应商.
If the order only has one vendor, then I only want to show the one vendor.
推荐答案
这个怎么样:
<% @order.line_items.all.group_by{|i| i.vendor}.each do |vendor, items| %>
<%= content_tag :h2, vendor.id %>
<ul>
<% items.each do |i| %>
<%= content_tag :li, i.id %>
<% end %>
</ul>
<% end %>
sort_by(&:vendor) 与 sort_by{|v| 相同v.vendor},但块式语法为您提供了更多的灵活性.例如,您可以在控制器中按供应商名称排序:
[edits]
sort_by(&:vendor) is the same as sort_by{|v| v.vendor}, but the block-style syntax gives you a little more flexibility. For example, you can sort by vendor name in the controller with:
@sorted = @order.line_items.all.group_by(&:vendor).sort_by{|vendor, items| vendor.name}
然后在视图中:
<% @sorted.each do |vendor, items| %>
<%= content_tag :h2, vendor.name %>
<ul>
<% items.each do |i| %>
<%= content_tag :li, i.id %>
<% end %>
</ul>
<% end %>
这篇关于Rails 3.1 :has_many, :through 复杂排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!