How do I automatically sort a has_many relationship in Rails?

前端 未结 5 1196
情书的邮戳
情书的邮戳 2020-12-12 13:02

This seems like a really simple question but I haven\'t seen it answered anywhere.

In rails if you have:

class Article < ActiveRecord::Base 
  has         


        
5条回答
  •  一生所求
    2020-12-12 13:40

    As of Rails 4, you would do:

    class Article < ActiveRecord::Base 
      has_many :comments, -> { order(created_at: :desc) }
    end 
    class Comment < ActiveRecord::Base 
      belongs_to :article 
    end
    

    For a has_many :through relationship the argument order matters (it has to be second):

    class Article
      has_many :comments, -> { order('postables.sort' :desc) }, 
               :through => :postable
    end
    

    If you will always want to access comments in the same order no matter the context you could also do this via default_scope within Comment like:

    class Comment < ActiveRecord::Base 
      belongs_to :article 
      default_scope { order(created_at: :desc) }
    end
    

    However this can be problematic for the reasons discussed in this question.

    Before Rails 4 you could specify order as a key on the relationship, like:

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

    As Jim mentioned you can also use sort_by after you have fetched results although in any result sets of size this will be significantly slower (and use a lot more memory) than doing your ordering through SQL/ActiveRecord.

    If you are doing something where adding a default order is cumbersome for some reason or you want to override your default in certain cases, it is trivial to specify it in the fetching action itself:

    sorted = article.comments.order('created_at').all
    

提交回复
热议问题