1

I have a Deal model that has_many :clicks. I want to sort some deals:

@deals = current_user.deals

by how many clicks they have. How can I do that? Click has deal_id as a field of course.

settheline
  • 3,333
  • 8
  • 33
  • 65

2 Answers2

2

This may be a prime candidate for a scope. You can do something like this in Deals.rb:

scope :sorted, -> { sort_by(:clicks_count) }

You can then call:

Deals.sorted OR current_user.deals.sorted

You can even use a default scope if you always want to sort on that field no matter what:

default_scope, -> { sort_by(:clicks_count) }
Carlos Cervantes
  • 1,377
  • 1
  • 10
  • 16
1

I would add a counter_cache to the Deal model to avoid improve database queries. For more information about counter_cache see: http://guides.rubyonrails.org/association_basics.html#counter-cache

Than it is just:

current_user.deals.order(:clicks_count)

# or when deals are already loaded
current_user.deals.sort_by(:clicks_count)
spickermann
  • 100,941
  • 9
  • 101
  • 131