wsm*_*wsm 5 ruby sorting ruby-on-rails
我希望按日期降序排序我的列表作为"新用户列表",在数据库中我有一个列是
t.datetime "created_at", null: false
Run Code Online (Sandbox Code Playgroud)
这是新用户注册的时间,在视图中,我有这样的代码:
%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'}
Run Code Online (Sandbox Code Playgroud)
但是这给出了一个错误"nil:NilClass的未定义方法`sort'",我该如何按表创建日期对表中的列表进行排序呢?谢谢.
Sur*_*rya 15
在你的控制器中:
@users = User.order('created_at DESC')
Run Code Online (Sandbox Code Playgroud)
只需添加: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'}
Run Code Online (Sandbox Code Playgroud)
您看到的错误是因为@created_at它不是可枚举的对象,因此它不响应sort.