如何订购通过聚合函数中的表,红宝石?(How to order a table by aggrega

2019-10-31 22:32发布

我有2个属性opening_dateclosing_date在招标模式。 在索引页我的显示是指其余日期( closing_date-Date.today )。 然而,剩下的日期不保存在数据库中,但我想秩序,其余日期显示在表中的数据。 我应该怎么使用? 是否有该聚合函数?

我使用Ruby 1.9.2和Rails 3.2.2

// 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

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

Answer 1:

你可以使用sort_by ,但这是在Ruby端,因此对大数据集慢(数据库应该处理)。 使用closing_date > NOW():order_by



文章来源: How to order a table by aggregate function in a ruby?