yaru
yaru

Reputation: 1310

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

Upvotes: 0

Views: 125

Answers (3)

army_coding
army_coding

Reputation: 154

Try the following :

has_many :box_chocolates, -> { order 'chocolates.name' }, through: :chocolate

Upvotes: 1

widjajayd
widjajayd

Reputation: 6253

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

Upvotes: 2

Rakesh Patidar
Rakesh Patidar

Reputation: 196

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

Upvotes: 1

Related Questions