在Rails中进行分组和排序,并显示最近突出显示的内容

时间:2014-05-22 02:47:30

标签: sql ruby-on-rails ruby

我有多个附件模型。我需要按附件类型对它们进行排序。我们有3种类型A,B和C.从那里我必须突出显示每种类型的最新附件,然后在其下面有另一个不是最近的附件。当设置附件时,类型来自A,B和C类型的下拉列表。我尝试过使用group by并按功能排序,但我不相信我正确使用它们。

我当前的代码

- @attachment.each do |attachment|
      %attachment-container
        .main-attachment
          %ul.inline
            %li
              %h3= attachment.attachment_type
              %dl
                %dd
                  Uploaded By
                  %span= attachment.uploader_name
                %dd
                  •
                %dd
                  = attachment.created_at
                %dd
                  •
                %dd
                  %button.add View previous attachments
              %p 
                = attachment.description    
            %li
              %a.btn.primary{:href => "#{attachment.url}"} Download       
        .more-reports{:style => "display: none"}(Should show least recent attachments of this type)
          %dl
            %dd
              Uploaded By
              %span= attachment.uploader_name
            %dd
              •
            %dd
              = attachment.created_at
            %dd
              •
            %li
              %a.btn.primary{:href => "#{attachment.url}"} Download

我认为我需要做的是......(删除CSS)

-@attachment.attachment_type.each do |attachment|
    -attachment.attachment_type
    -attachment.each do
        -attachment.uploader_name
        -attachment.created_at(somehow needs to be only most recent)
        Download button here
        Somehow needs to be other not recent files.

1 个答案:

答案 0 :(得分:0)

首先,为变量@attachments命名,而不是@attachment

在您的控制器中,您可以按照类似

的类型对附件进行分组
@attachments_by_type = @attachments.group_by(&:attachment_type)
@sorted_attachments_by_type = @attachments_by_type.inject({}) {|h, (k, v)| h[k] = v.sort_by{|a| -a.created_at; h}}

现在您有一个带键的哈希作为类型和值作为已排序的附件数组。您可以在下面的视图中使用它

-@sorted_attachment_by_type.each do |type, attachments|
    -type
    -recent_attachment = attachments.shift
    -recent_attachment.uploader_name
    -recent_attachment.created_at(most recent)
    -Download button
    -attachments.each do
        -attachment.uploader_name
        -attachment.created_at(least recent)