How do I automatically sort a has_many relationship in Rails?

前端 未结 5 1204
情书的邮戳
情书的邮戳 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:17

    You can specify the sort order for the bare collection with an option on has_many itself:

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

    Or, if you want a simple, non-database method of sorting, use sort_by:

    article.comments.sort_by &:created_at
    

    Collecting this with the ActiveRecord-added methods of ordering:

    article.comments.find(:all, :order => 'created_at DESC')
    article.comments.all(:order => 'created_at DESC')
    

    Your mileage may vary: the performance characteristics of the above solutions will change wildly depending on how you're fetching data in the first place and which Ruby you're using to run your app.

提交回复
热议问题