0

Is there a way to use a model association inside the :order part of a Rails find? For example, I have the following scenario:

User
  has_many :lists
end

#fields include: count is an int, best is a boolean and only only list has best equal true
List
  belongs_to :user      
end

I would like to perform a find that orders the users by the count value of the users best list. I know this totally doesn't work, but maybe it will help get my goal across:

User.find_all_by_id_and_profile(user_ids, true, :order => "user.lists.find_by_best(true).count")

I've read about using :include, but I'm not sure how that would apply here.

TenJack
  • 1,594
  • 4
  • 21
  • 35
  • 1
    Can you please clarify what you mean by "count value of the list that has best set to true" – Toby Hede Jan 30 '11 at 09:01
  • Hi Toby, I totally miss typed that, I would like to order the users by the count of their best list. – TenJack Jan 30 '11 at 10:26
  • Maybe this might give you a hint: http://stackoverflow.com/questions/1760404/order-products-by-association-count – polarblau Jan 30 '11 at 11:23
  • That does help, but what if you are looking for a specific object, like :include => :lists (but I only want the list that has best set to true). – TenJack Jan 30 '11 at 12:18

1 Answers1

1

So if I understand correctly you try to order the users from their list's best attribute count. I guess you have to use a subquery.

User.where("users.id IN (?) AND profile=true", user_ids).order(
 '(SELECT COUNT(*) FROM lists WHERE (best=true) AND (users.id=lists.user_id))')
dombesz
  • 7,890
  • 5
  • 38
  • 47