0

我有 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>
4

1 回答 1

1

您可以使用sort_by,但这是在 ruby​​ 方面,因此在大型数据集上速度很慢(数据库应该处理)。使用closing_date > NOW()和一个:order_by.

于 2012-07-14T20:47:00.593 回答