[英]order by association
这是我的模特。
Restaurant has many patrons
patrons have many transactions
在管制员索引中,所有顾客都喜欢
@pts = Restaurant.find(1).patrons
鉴于我只列出了顾客属性,包括每个顾客的交易次数,例如
我如何按每个顾客的交易计数来排序结果集(@pts)?
谢谢
假设您没有太多的顾客,并且不使用计数缓存( transactions_counter
),则可以这样做:
@pt.sort_by{|p|p.transactions.count}.each do |patron|
...
或者您可以设置一个计数器缓存并在sql中进行(您可以不使用它,但是查询会更麻烦)
将transactions_counter添加到顾客表,然后
class Patron < ActiveRecord::Base
has_many :transactions, :counter_cache => true
#...
end
然后,您可以在查询中对其进行排序:
@pts = Restaurant.find(1).patrons.all :order => "patrons.transactions_counter DESC"
您甚至可以将其添加到has_many调用中并简化操作。
这将按ID排序。 将其放入模型中。
has_many :patrons, :order => "id DESC"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.