【问题标题】:How to sort table columns in rails?如何对rails中的表格列进行排序?
【发布时间】:2013-02-03 01:27:11
【问题描述】:

我按照 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);
}

【问题讨论】:

  • 您描述的排序最好在 Javascript 中实现,因为它基本上是客户端问题(而 rails 可以帮助解决服务器端问题)。 jquery 的表格排序器插件正是您正在寻找的:tablesorter.com/docs.
  • 嗨@Reck,谢谢你的推荐。我想探索用 Rails 做这件事的可能性,作为一个学习过程。
  • 您想要的产品列表中的默认排序是什么??

标签: ruby-on-rails-3


【解决方案1】:

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

【讨论】:

  • 目前,ransack 不适用于 edge RoR。 github.com/activerecord-hackery/polyamorous/issues/6
  • 如果您遇到polyamorous 的问题,请尝试将其添加到您的 gem 文件中。 gem 'polyamorous', github: 'activerecord-hackery/polyamorous'
  • gem "ransack", github: "activerecord-hackery/ransack", branch: "rails-4.1" gem 'polyamorous', github: 'activerecord-hackery/polyamorous'
【解决方案2】:

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

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

【讨论】:

  • 不再积极维护 gem。作者提到他不会为此工作,它正在寻找维护者。
  • 它有一个 Rails 5 分支。因此,如果您担心使用它没有得到维护,原作者缺乏维护不再是主要问题。
【解决方案3】:

您可以尝试对 index 方法进行 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    相关资源
    最近更新 更多