gpt4 book ai didi

ruby-on-rails - 在 ruby​​ in rails 中按日期降序排序

转载 作者:数据小太阳 更新时间:2023-10-29 07:10:02 24 4
gpt4 key购买 nike

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

t.datetime "created_at",                                      null: false  

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

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

但是这给出了一个错误,“undefined method ‘sort’ for nil:NilClass”,我应该怎么做才能按创建日期降序对表中的列表进行排序?谢谢。

最佳答案

在你的 Controller 中:

@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 .

关于ruby-on-rails - 在 ruby​​ in rails 中按日期降序排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36083303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com