【问题标题】:How do I automatically sort a has_many relationship in Rails 4?如何在 Rails 4 中自动排序 has_many 关系?
【发布时间】:2014-10-07 15:22:46
【问题描述】:

我找到了一个answer,但它已经过时了(2009 年)。

我想知道如何根据 has_many 关系对集合进行排序,最好是在模型中。

类似这样的:

class Article < ActiveRecord::Base 
  has_many :comments, :order => 'created_at DESC'
end 

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4


    【解决方案1】:

    你试过了吗:

    class Article < ActiveRecord::Base 
      has_many :comments, -> { order "created_at DESC" } 
    end 
    

    【讨论】:

      【解决方案2】:

      当您迁移到 Rails 4 版本时,有许多语法更改。 检查这个:

      http://edgeguides.rubyonrails.org/association_basics.html#scopes-for-has-many

      【讨论】:

        猜你喜欢
        • 2010-10-18
        • 2023-04-06
        • 2014-10-23
        • 1970-01-01
        • 1970-01-01
        • 2023-03-29
        • 2015-10-12
        • 1970-01-01
        • 2013-07-27
        相关资源
        最近更新 更多