【问题标题】:Specifying the default ordering for a has_many association using a join (Rails)?使用连接(Rails)为 has_many 关联指定默认排序?
【发布时间】:2012-09-17 05:05:40
【问题描述】:

我有一个简单的 Customer 模型,它与 Purchase 模型有很多关系。

class Customer < ActiveRecord::Base
  has_many :purchases
end

我反复发现我需要通过以下方式在我的视图中订购 Customer.purchases:

@customer.purchases.joins(:shop).order("shops.position").order(:position) #yes, two orders chained

为了保持干燥,我想把它放在一个集中的地方,这样我就不必重复做。理想情况下,我想让它成为 Customer.purchases 的默认排序。例如:

class Customer < ActiveRecord::Base
  has_many :purchases, :order => joins(:shop).order("shops.position").order(:position)
end

显然以上方法行不通。我该怎么做?

【问题讨论】:

    标签: ruby-on-rails sql-order-by rails-activerecord


    【解决方案1】:

    在您的客户模型中,您指定 joins(:shop) 是键 :order 的值。我认为这是问题所在,因此您可以使用 joins 作为键而不是像下面这样的顺序,

    class Customer < ActiveRecord::Base
      has_many :purchases, :joins => [:shop], :order => "shops.position"
    end
    

    我认为它可能有效。

    【讨论】:

    • 似乎不起作用。给我一个undefined method `key?' for nil:NilClass 错误。
    【解决方案2】:

    在您的购买模型中,您可以创建一个类方法:

    Purchase.rb:

    def self.order_by_position
      joins(:shop).order("shops.position").order(:position)
    end
    

    然后你可以这样说:

    @customer.purchases.order_by_position
    Purchase.order_by_position
    

    【讨论】:

      【解决方案3】:

      您可以在Customer 上创建一个返回已订购商品的方法:

      class Customer < ActiveRecord::Base
        has_many :purchases
      
        def ordered_purchases
          purchases.joins(:shop).order("shops.position").order(:position)
        end
      end
      

      并在您的意见中致电@customer.ordered_purchases

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-09
        • 1970-01-01
        • 1970-01-01
        • 2016-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多