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.
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.
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) }
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)