0

I have two models:

jacket.rb:

  has_many :button
  belongs_to :store

button.rb:

belongs_to :jacket

In my store controller, I want to be able to do @store.jackets.order(buttons: :desc), but I cannot do this because it is not a db column. How would I do it?

delisdeli
  • 839
  • 9
  • 20

1 Answers1

0

You need to write some SQL in order to count the association, alias the count to a name, and order by that name:

@store.jackets.joins(:buttons).select("jackets.*, COUNT(buttons.id) as button_total").order('button_total DESC')

More on sql counts here

DiegoSalazar
  • 13,361
  • 2
  • 38
  • 55