Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort table columns in rails?

I implemented this following the Ryan Bates tutorial to sort table columns and it works great, however when I render the index page the table is already sorted by title (asc), and I would like to sort the columns only when the user click on the column header.

How could I achieve this?

Code

controller

class ProductsController < ApplicationController
  helper_method :sort_column, :sort_direction

  def index
    @products = Product.order(sort_column + " " + sort_direction)
  end

  # ...

  private

  def sort_column
    Product.column_names.include?(params[:sort]) ? params[:sort] : "name"
  end

  def sort_direction
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
  end
end

helper_method

def sortable(column, title = nil)
  title ||= column.titleize
  css_class = column == sort_column ? "current #{sort_direction}" : nil
  direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
  link_to title, {:sort => column, :direction => direction}, {:class => css_class}
end

index.html.erb

<tr>
  <th><%= sortable "name" %></th>
  <th><%= sortable "price" %></th>
  <th><%= sortable "released_at", "Released" %></th>
</tr>

CSS

.pretty th .current {
  padding-right: 12px;
  background-repeat: no-repeat;
  background-position: right center;
}

.pretty th .asc {
  background-image: url(/images/up_arrow.gif);
}

.pretty th .desc {
  background-image: url(/images/down_arrow.gif);
}
like image 862
evanx Avatar asked Dec 26 '22 10:12

evanx


2 Answers

You should check out Ransack. It does a great job for sorting and complex searches. There is a great RailsCasts video that should help you and is much less invasive.

like image 185
kobaltz Avatar answered Feb 28 '23 02:02

kobaltz


Just in case someone will find this question. There is a a great gem for sortable columns (and not only that): https://github.com/leikind/wice_grid

Just look at the examples: http://wicegrid.herokuapp.com/

like image 27
Extrapolator Avatar answered Feb 28 '23 03:02

Extrapolator