【发布时间】:2019-07-11 13:12:10
【问题描述】:
如何按其关联模型之一订购记录?在下面的代码中访问.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 类中创建了一个自定义方法,但我不喜欢它的工作方式 - 它使用 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
【问题讨论】:
标签: ruby-on-rails activerecord ruby-on-rails-5 rails-activerecord