Order and limit

I need to make the following query:

SELECT * FROM "specimens" ORDER BY distribution_sheet_id DESC LIMIT 10 

and I set:

 <%= Specimen.last(:order => :distribution_sheet_id).id %> 

I like to output "limit 10" rather than limit 1. I suppose its .last, but can I express it differently to limit 10.

thanks

+4
source share
2 answers

Assuming you are using Rails 3

 <%= Specimen.limit(10).order("distribution_sheet_id").all %> 

Note that if you limit more than 1 entry, you cannot call #id at the end, because the result is an array.

To get all identifiers

 <%= Specimen.limit(10).order("distribution_sheet_id").map(&:id) %> 

For Rails 2.3, use the old hash conditions.

 <%= Specimen.all(:order => "distribution_sheet_id", :limit => 10) %> 

and the same goes for id

 <%= Specimen.all(:order => "distribution_sheet_id", :limit => 10).map(&:id) %> 

Here I use the #to_sentence method to join all IDs. Adapt the code according to your use case.

 <%= Specimen.all(:order => "distribution_sheet_id", :limit => 10).map(&:id).to_sentence %> 
+5
source
 <ul> <% Specimen.find(:all, :order => 'distribution_sheet_id desc', :limit => 10).each do |specimen| %> <li><%= specimen.id %></li> <% end %> </ul> 
+1
source

Source: https://habr.com/ru/post/1346549/


All Articles