如何按关联对记录排序?

时间:2019-07-11 13:12:10

标签: ruby-on-rails activerecord ruby-on-rails-5 rails-activerecord

如何通过其关联模型之一对记录进行排序?在下面的代码中,访问.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

3 个答案:

答案 0 :(得分:2)

您可以在下面的示例框中创建范围或方法

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

尝试以下方法:

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