在rails中实现sort asc或desc的最佳方法 [英] Best way to implement sort asc or desc in rails

查看:386
本文介绍了在rails中实现sort asc或desc的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rails的视图/控制器中是否存在一种优雅的方式来实现排序asc和desc动作?

Is there an elegant way to implement a sort asc and desc actions in the views/controller in rails?

我所拥有的是常见的index.html.erb视图,该视图列出了特定模型的所有数据,并且我想添加一些小按钮(或使标题可单击)以对该列的升序或降序进行排序.我想知道是否有一种优雅而有效的方法来执行此操作,还是应该为要执行此操作的每个列(或按钮)添加一个新的控制器.

What I have is the common index.html.erb view that lists all of my data of certain model and I want to add some small buttons (or make the title clickable) to sort the list ascending or descending of that column. I am wondering if there is an elegant and efficient way to do it or should I just add a new controller for every column (or button) I want this action to happen.

推荐答案

以下是我正在使用的两个示例. @plans的第一个是我只想从最低到最高排序一个小数的地方.另一个示例有点复杂,我要从最新到最旧的顺序对用户文件进行排序.然后,我使用第二个变量按创建日期对文件进行分组.这两个示例都在控制器中执行.

Here are two examples that I'm using. The first one with @plans is where I just want to order a decimal from lowest to highest. The other example is a bit more complicated where I want to order user files from newest to oldest. I then used a second variable to group the files by the date created. Both examples where performed in the controllers.

@plans = Plan.order("price")

@files= @user.files.order("id DESC").all
@dates = @files.group_by { |t| t.created_at }

要查看视图中可单击的按钮,请查看Ryan Bates的Railscast专题,其中包含此信息.

For clickable buttons in your view, check out Ryan Bates's Railscast episode covering this information.

http://railscasts.com/episodes/228-sortable-table-columns

这篇关于在rails中实现sort asc或desc的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆