簡體   English   中英

在rails中的ruby中按降序按日期排序

[英]Sort by date in descending order in ruby in rails

我想按日期按降序對我的列表進行排序,作為“新用戶列表”,在數據庫中我有一列是

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

但這給出了一個錯誤,即“未定義的方法`sort' for nil:NilClass”,我該怎么做才能按創建日期降序對表中的列表進行排序? 謝謝。

在您的控制器中:

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

只需在您獲取@users邏輯中添加: order('created_at DESC')

在您看來,您現在可以擺脫- @created_at.sort{|a,b| b.created_at <=> a.created_at}.each - @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

這是因為@created_at沒有在任何地方定義。 因此,任何未定義的實例變量默認返回 nil。 如果要按排序順序顯示用戶,則需要按順序獲取@users

@users = User.order(created_at: :desc)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM