【问题标题】:How to sort records by association?如何按关联对记录进行排序?
【发布时间】: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


    【解决方案1】:

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

    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
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 虽然您的代码可能会提供问题的答案,但请在其周围添加上下文,以便其他人了解它的作用以及它存在的原因。
      • 我的代码的问题是我使用了“chocolate.name”而不是“chocolates.name”。谢谢!
      • @yaru 你的意思是has_many :box_chocolates, -&gt; { order("chocolates.name") } 为你工作?
      • 不,我的意思是您的线路按原样为我工作。不是 has_many 语句的一部分。
      【解决方案3】:

      尝试以下方法:

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

      【讨论】:

      • 这是一个很好的方法,尽管我认为应该反过来:has_many :chocolates, through: :box_chocolates, etc...,不是吗?
      • 按照惯例,是的!但是根据给定的代码 sn-p,这个人到底需要做什么。
      • @DhanashriJoshi 得到ArgumentError: Unknown key: :order.
      • @DhanashriJoshi 没有收到syntax error, unexpected '\n', expecting =&gt;
      • has_many :box_chocolates, -> { order 'chocolates.name' }, through: :chocolate
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 2021-07-06
      • 1970-01-01
      • 2020-04-16
      • 1970-01-01
      相关资源
      最近更新 更多