docs/docs/getting-started/sorting


title: Sorting

Sorting

Sorting in the View

You can add a form to capture sorting and filtering options together.

# app/views/posts/index.html.erb

<%= search_form_for @q do |f| %>
  <%= f.label :title_cont %>
  <%= f.search_field :title_cont %>

  <%= f.submit "Search" %>
<% end %>


    <% @posts.each do |post| %>

    <% end %>



      <%= sort_link(@q, :title, "Title") %>
      <%= sort_link(@q, :category, "Category") %>
      <%= sort_link(@q, :created_at, "Created at") %>




        <%= post.title %>
        <%= post.category %>
        <%= post.created_at.to_s(:long) %>


Sorting in the Controller

To specify a default search sort field + order in the controller index:

# app/controllers/posts_controller.rb
class PostsController < ActionController::Base
  def index
    @q = Post.ransack(params[:q])
    @q.sorts = 'title asc' if @q.sorts.empty?

    @posts = @q.result(distinct: true)
  end
end

Multiple sorts can be set by:

# app/controllers/posts_controller.rb
class PostsController < ActionController::Base
  def index
    @q = Post.ransack(params[:q])
    @q.sorts = ['title asc', 'created_at desc'] if @q.sorts.empty?

    @posts = @q.result(distinct: true)
  end
end