Skip to main content

sorting_results

Quickly enable column sorting using sort_link. Clicking the header will toggle ASC/DESC automatically.

<table>
<thead>
<tr>
<th><%= sort_link(@q, :name, "Name") %></th>
<th><%= sort_link(@q, :created_at, "Joined At") %></th>
</tr>
</thead>
<tbody>
<% @products.each do |product| %>
<tr>
<td><%= product.name %></td>
<td><%= product.created_at.to_date %></td>
</tr>
<% end %>
</tbody>
</table>

Ensure your controller uses the sorted result:

@q = Product.ransack(params[:q])
@products = @q.result.order(@q.sorts)