Reputation: 1310
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
Reputation: 154
Try the following :
has_many :box_chocolates, -> { order 'chocolates.name' }, through: :chocolate
Upvotes: 1
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
Reputation: 196
b.box_chocolates.joins(:chocolate).order("chocolates.name asc")
Upvotes: 1