我在投标模型中有2个属性opening_date
和closing_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>
答案 0 :(得分:1)
你可以使用sort_by
,但那是在红宝石方面,因此对大型数据集来说很慢(数据库应该处理它)。使用closing_date > NOW()
和:order_by
。