Get all identifiers from the collection

I got my collection items as follows:

hotels = Hotel.where('selection = ?', 1).limit(4) 

How can I get all the identifiers of these elements without a loop? Can I use something like:

 hotels.ids ? 

thanks

+6
source share
4 answers

What about trying hotels.map(&:id) or hotels.map{|h| h.id } hotels.map{|h| h.id } ?

Both of them mean the same thing to Ruby, the first of them is better than other familiar rubies, while the second is easier to understand for beginners.

+17
source

If you only need an array with all identifiers, you should use pluck , since it makes the correct request, t should use any ruby. In addition, he does not need to create an instance of the hotel object for each record returned from the database. (faster).

 Hotel.where(selection: 1).pluck(:id) # SELECT hotels.id FROM hotels WHERE hotels.selection = 1 # => [2, 3] 
+11
source

If you use Rails> 4, you can use the ids method:

 Person.ids # SELECT people.id from people 

Additional information: http://apidock.com/rails/ActiveRecord/Calculations/ids

+9
source

You can also pull only identifiers.

 hotels.select(:id).where(selection: 1) 
+7
source

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


All Articles