开发者

order by association

开发者 https://www.devze.com 2023-01-04 13:10 出处:网络
Here are my models. Restaurant has many patrons patrons have many transactions In controller index all patrons like

Here are my models.

Restaurant has many patrons
patrons have many transactions

In controller index all patrons like

@pts = Restaurant.find(1).patrons

and in view I simply list the patrons attributes, inluding number开发者_JS百科 of transaction per patrons like

How would I order the resultset (@pts) by transaction count of each patron?

Thanks


Assuming you don't have too many patrons and you don't use a count cache (transactions_counter), you could do it like this:

@pt.sort_by{|p|p.transactions.count}.each do |patron|
...

Or you could set up a counter cache and do it in sql(you can do it without but the queries are a bit more annoying)

add transactions_counter to the patrons table and

class Patron < ActiveRecord::Base
  has_many :transactions, :counter_cache => true
  #...
end

Then you can sort by it in your query:

@pts = Restaurant.find(1).patrons.all :order => "patrons.transactions_counter DESC"

You could even add that to your has_many call and simplify things.


This will order by id. Put it in the model.

  has_many :patrons, :order => "id DESC"
0

精彩评论

暂无评论...
验证码 换一张
取 消