如何按关联对记录进行排序?
How to sort records by association?
如何按其关联模型之一对记录进行排序?在下面的代码中,当访问 .box_chocolates
关联时,我需要它到按 Chocolate#name
:
排序的 return 记录
b = Box.first
b.box_chocolates # <-- records must be ordered by Chocolate#name
模型结构:
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
我在 Box class 中创建了一个自定义方法,但我不喜欢它的工作方式 - 它使用 Ruby 对记录进行排序而不是 SQL 查询:
def ordered_box_chocolates
box_chocolates.sort { |a, b| a.chocolate.name <=> b.chocolate.name }
end
我知道我可以像下面的代码一样在 has_many
中指定顺序,但它不起作用:
class Box < ApplicationRecord
has_many :box_chocolates, -> { order("chocolate.name") }
end
b.box_chocolates.joins(:chocolate).order("chocolates.name asc")
您可以在框中创建作用域或方法,如下例
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
尝试以下操作:
has_many :box_chocolates, -> { order 'chocolates.name' }, through: :chocolate
如何按其关联模型之一对记录进行排序?在下面的代码中,当访问 .box_chocolates
关联时,我需要它到按 Chocolate#name
:
b = Box.first
b.box_chocolates # <-- records must be ordered by Chocolate#name
模型结构:
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
我在 Box class 中创建了一个自定义方法,但我不喜欢它的工作方式 - 它使用 Ruby 对记录进行排序而不是 SQL 查询:
def ordered_box_chocolates
box_chocolates.sort { |a, b| a.chocolate.name <=> b.chocolate.name }
end
我知道我可以像下面的代码一样在 has_many
中指定顺序,但它不起作用:
class Box < ApplicationRecord
has_many :box_chocolates, -> { order("chocolate.name") }
end
b.box_chocolates.joins(:chocolate).order("chocolates.name asc")
您可以在框中创建作用域或方法,如下例
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
尝试以下操作:
has_many :box_chocolates, -> { order 'chocolates.name' }, through: :chocolate