2016-03-18 72 views
3

我想按日期排序,我在降序列表,它作为一个“新用户列表”,在数据库中我有一列是按日期排序在Ruby中降序排列轨

t.datetime "created_at",          null: false 

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

%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'} 

,但是这给了“为无未定义的方法`排序”:NilClass”的错误,我拿什么是否按创建日期降序对表中的列表进行排序?谢谢。

+0

对于那些低估了这个问题的人,请向提问的人提供可操作的反馈,以便他们改进。让我们的社区更加棒! – Justin

回答

12

在你的控制器:

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

只需添加:order('created_at DESC')在你的逻辑,你要提取@users

在您看来,您现在可以摆脱掉- @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回应。

+1

你也可以使用'User.order(created_at :: desc)' –