问题
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?
I am using Ruby 1.9.2 and 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
//Tender Model
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>
回答1:
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.
来源:https://stackoverflow.com/questions/11487130/how-to-order-a-table-by-aggregate-function-in-a-ruby