如何在rails中对表列进行排序?

时间:2013-02-03 01:27:11

标签: ruby-on-rails-3

我按照Ryan Bates教程向sort table columns实现了这个并且它工作得很好,但是当我渲染索引页时,表已经按标题(asc)排序了,我想只对列进行排序用户单击列标题。

我怎么能实现这个目标?

代码

控制器

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);
}

3 个答案:

答案 0 :(得分:6)

你应该看看Ransack。它在排序和复杂搜索方面做得很好。有一个很棒的RailsCasts视频可以帮助你,并且侵入性更小。

答案 1 :(得分:2)

万一有人会发现这个问题。可排序列有一个很棒的宝石(不仅如此):https://github.com/leikind/wice_grid

看看这些例子: http://wicegrid.herokuapp.com/

答案 2 :(得分:1)

您可以尝试对索引方法进行if检查

def index
  if sort_column and sort_direction
    @products = Product.order(sort_column + " " + sort_direction)
  else
    @products = Product.all()
  end
end

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

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