在rails中的ruby中按降序按日期排序 [英] Sort by date in descending order in ruby in rails

查看:55
本文介绍了在rails中的ruby中按降序按日期排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按日期降序对我的列表进行排序,作为新用户列表",在数据库中我有一列是

I would like to sort my list in a descending order by date which as a "New user list", in the database I have a column which is

t.datetime "created_at",                                      null: false  

这是新用户注册的时候,在视图中,我有这样的代码:

This is the time when a new user registered, in the view, I have the code like this:

%table.table.table-striped.table-hover
      %thead
      %h3 New Users
      %hr
        %th Name
        %th Company
        %th Role
        %th Created date
        %th{:width => '50'}
        %th{:width => '50'}
        %th{:width => '50'}
      %tbody
      - @users.each do |user|
        -if user.role == "trial-member"
          - @created_at.sort{|a,b| b.created_at <=> a.created_at}.each do |created_at|
            %tr
            %td
              = user.first_name
              = user.last_name
            %td= user.company
            %td= user.role
            %td= user.created_at
            %td= link_to 'Approve', edit_user_path(user),  {:class => 'btn btn-success btn-sm'}

但是这给出了一个错误未定义的方法`sort' for nil:NilClass",我应该怎么做才能按创建日期降序对表中的列表进行排序?谢谢.

but this gives an error that "undefined method `sort' for nil:NilClass", what shall I do to sort the list in table descending by created date? Thank you.

推荐答案

在你的控制器中:

@users = User.order('created_at DESC')

只需在您获取 @users 的逻辑中添加:order('created_at DESC').

Just add: order('created_at DESC') in your logic where you're fetching @users.

在您看来,您现在可以摆脱 -@created_at.sort{|a,b|b.created_at <=>a.created_at}.each:

In your view, you can now get rid off of - @created_at.sort{|a,b| b.created_at <=> a.created_at}.each:

%h3 New Users
%table.table.table-striped.table-hover
  %thead
    %tr
      %th Name
      %th Company
      %th Role
      %th Created date
      %th{:width => '50'}
      %th{:width => '50'}
      %th{:width => '50'}
  %tbody
    - @users.each do |user|
      -if user.role == "trial-member"
        %tr
          %td
            = user.first_name
            = user.last_name
          %td= user.company
          %td= user.role
          %td= user.created_at
          %td= link_to 'Approve', edit_user_path(user),  {:class => 'btn btn-success btn-sm'}

您看到的错误是因为 @created_at 不是可枚举对象,因此它不响应 sort.

Error you are seeing is because @created_at is not an enumerable object, hence it does not respond to sort.

这篇关于在rails中的ruby中按降序按日期排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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