开发者

How to sort when fetching a collection of models?

开发者 https://www.devze.com 2023-03-10 22:55 出处:网络
I have a call on my posts_controller.rb index action: @articles = Article.order(\"id desc\") I now want to be able to order by:

I have a call on my posts_controller.rb index action:

@articles = Article.order("id desc")

I now want to be able to order by:

date
id
some_counter_attribute

My querystr开发者_运维知识库ing will have sort=date/id/count like:

www.example.com/articles/?sort=date

How should I implement this in my controller now? Should I just use if statements?

if params[:sort] == "date"
  @articles = Article.order("created_at desc")
elsif params[:sort] == "count"
  @articles = ...
..

Or is there a better way? Should this logic be in the controller or Model ideally?


Try this:

class ArticlesController

  def index
    @articles = Article.order(sort_order)
  end        

private

  def sort_order
    @@sort_order ||= { 
      "date" => "created_at DESC",
      "id"   => "id DESC",
      "comments" => "comment_count ASC"
    }
    @@sort_order[params[:sort]]
  end

end

Off course there are gems for doing this sort of things:

MetaSearch

SearchLogic


Straightforward approach could be:

@articles = Article.order("#{params[:sort]} desc")

But for "date" you have to sort by created_at. So try this:

mylist = {"date" => "created_at",
          "id" => "id",
          "counter" => "some_counter_attribute"}

@articles = Article.order("#{mylist[params[:sort]]} desc")
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号