order by and limit
I need to do the following query:
SELECT * FROM "specimens" ORDER BY distribution_sheet_id DESC LIMIT 10
and I have put开发者_如何学编程:
<%= Specimen.last(:order => :distribution_sheet_id).id %>
I like to output 'limit 10' not limit 1. I suppose its the .last, but can I express it in other way to limit 10.
Thanks
Assuming you are using Rails 3
<%= Specimen.limit(10).order("distribution_sheet_id").all %>
Please note that if you limit to more than 1 record, you can't call #id
at the end because the result is an array.
To get all the ids
<%= Specimen.limit(10).order("distribution_sheet_id").map(&:id) %>
For Rails 2.3 use the old hash-based conditions.
<%= Specimen.all(:order => "distribution_sheet_id", :limit => 10) %>
and the same applies for the id
<%= Specimen.all(:order => "distribution_sheet_id", :limit => 10).map(&:id) %>
Here I'm using the #to_sentence
method to join all ID. Adapt the code according to your use case.
<%= Specimen.all(:order => "distribution_sheet_id", :limit => 10).map(&:id).to_sentence %>
<ul>
<% Specimen.find(:all, :order => 'distribution_sheet_id desc', :limit => 10).each do |specimen| %>
<li><%= specimen.id %></li>
<% end %>
</ul>
精彩评论