在rails中实现sort asc或desc的最佳方法

编程入门 行业动态 更新时间:2024-10-22 15:35:51
本文介绍了在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.

railscasts/episodes/228-sortable-table-columns

更多推荐

在rails中实现sort asc或desc的最佳方法

本文发布于:2023-10-23 05:55:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519987.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   sort   rails   desc   asc

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!