Mike
Mike

Reputation: 53

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

Upvotes: 4

Views: 8264

Answers (2)

Omar Qureshi
Omar Qureshi

Reputation: 9093

<ul>
<% Specimen.find(:all, :order => 'distribution_sheet_id desc', :limit => 10).each do |specimen| %>
  <li><%= specimen.id %></li>
<% end %>
</ul>

Upvotes: 1

Simone Carletti
Simone Carletti

Reputation: 176412

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

Upvotes: 5

Related Questions