在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的最佳方法
发布评论