How to sort records by association?

by yaru   Last Updated July 12, 2019 05:26 AM

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


Answers 3


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

Rakesh Patidar
Rakesh Patidar
July 11, 2019 13:44 PM

you can create scope or method in box as sample below

class Box < ApplicationRecord
  has_many :box_chocolates 

  def self.box_chocolates_ordered
    joins(box_chocolates: :chocolate).order('chocolates.name')
      # you have to use table name in plural form (chocolates)
  end
end

b = Box.first
b.box_chocolates_ordered
widjajayd
widjajayd
July 11, 2019 14:26 PM

Try the following :

has_many :box_chocolates, through: :chocolate, -> { order 'chocolates.name' }
Dhanashri Joshi
Dhanashri Joshi
July 11, 2019 14:33 PM

Related Questions


Updated June 01, 2017 14:26 PM

Updated October 25, 2017 22:26 PM

Updated March 12, 2019 00:26 AM

Updated August 16, 2018 21:26 PM

Updated March 21, 2019 12:26 PM