Search code examples
ruby-on-railsactiverecordruby-on-rails-5rails-activerecord

How to sort records by association?


How to order records by one of its associated models? In code below when accessing .box_chocolates association I need it to return records ordered by Chocolate#name:

b = Box.first
b.box_chocolates # <-- records must be ordered by Chocolate#name

Models structure:

class Box < ApplicationRecord
  has_many :box_chocolates # <--- ???
end

class BoxChocolate < ApplicationRecord
  belongs_to :box
  belongs_to :chocolate
end

# id    :integer
# name  :string
class Chocolate < ApplicationRecord      
end

I created a custom method in Box class but I don't like how it works - it uses Ruby to sort records instead of SQL query:

def ordered_box_chocolates
   box_chocolates.sort { |a, b| a.chocolate.name <=> b.chocolate.name }
end

I know that I can specify ordering in has_many like in code below, but it does not work:

class Box < ApplicationRecord
  has_many :box_chocolates, -> { order("chocolate.name") }
end

Solution

  • b.box_chocolates.joins(:chocolate).order("chocolates.name asc")