如何在ruby中通过聚集函数排序表? [英] How to order a table by aggregate function in a ruby?

查看:81
本文介绍了如何在ruby中通过聚集函数排序表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在投标模型中,我有2个属性 opening_date closing_date 。在索引页面上,我显示的是剩余日期( closing_date-Date.today )。但是,剩余日期未保存在数据库中,但我想按剩余日期排序并在表中显示数据。我应该使用什么?是否有一个汇总函数?

I have 2 attributes opening_date and closing_date in a Tender model. On the index page what I display is the remaining date which is (closing_date-Date.today). However, remaining date is not saved in a database but I wanted to order and display the data in the table by remaining date. What should I use? Is there an aggregate function for that?

我正在使用Ruby 1.9.2和Rails 3.2.2

I am using Ruby 1.9.2 and Rails 3.2.2

// TendersController

//TendersController

 def index
 @tenders= Tender.where("company_id= ? ", current_user.company.id).order('closing_date') 
/* Here I am querying the tender by closing_date but I dont want to do that. What I wanted is I just want to order by (closing_date-Date.today) which is not in the database but should be done on the fly. i.e the smallest the number it should be at the top of the table (index.html.erb) to notify the user the closing date is sooner than they think
*/
end

//投标模型

attr_accessible :title, :buyer_name, :category, :opening_date, :closing_date, :bid_amount, :description, :status

// index.htm.erb

//index.htm.erb

<table border="1" id="tender_table" >
  <tr class="table_header">
    <th>Title</th>
    <th>Buyer Name</th>
    <th>Remaining dates</th>
    <th>Status</th>
    <th>Bid amount</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

  <% @tenders.each do |tender| %>
<% day_diff= tender.closing_date.to_date-Date.today %>
<tr class=<%= tender.status %>> 
<td><%= tender.title %></td>
    <td><%= tender.buyer_name %></td>
    <td >

        <%  if day_diff < 0 %>
        <FONT COLOR="black"><%= -(day_diff).to_i %> days passed</td>

        <% else if day_diff > 10%>
            <FONT COLOR="green"><%= distance_of_time_in_words(tender.closing_date,Date.today) %></td>                   

        <% end %>
        <% end %>

        <% if day_diff <= 10 and day_diff>=0 %>
                <FONT COLOR="red"><%=distance_of_time_in_words(tender.closing_date,Date.today)+' ' %>left</td>

        <% end %>





    <td><%= tender.status %></td>
    <td><%= tender.bid_amount %></td>


    <%#  tender.description %>

    <td><%= link_to 'Show', tender %></td>
    <td><%= link_to 'Edit', edit_tender_path(tender) %></td>
    <td><%= link_to 'Destroy', tender, confirm: 'Are you sure?', method: :delete %></td>
  </tr>
<% end %>
</table>


推荐答案

您可以使用 sort_by ,但这在红宝石方面,因此在大型数据集上速度较慢(数据库应处理)。使用截止日期> NOW():order_by

You could use sort_by, but that's on the ruby side and therefore slow on large datasets (the database should handle that). Use closing_date > NOW() and an :order_by.

这篇关于如何在ruby中通过聚集函数排序表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆