Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all ids from a collection

I got my collection items like this :

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

How can I get all ids of this items without a loop? Can i use something like :

hotels.ids ? 

Thank you

like image 217
Sebastien Avatar asked Oct 03 '11 14:10

Sebastien


2 Answers

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

They both mean the same thing to Ruby, the first one is nicer to accustomed ruby-ists usually, whilst the second one is easier to understand for beginners.

like image 160
Romain Avatar answered Sep 20 '22 00:09

Romain


If you only need an array with all the ids you should use pluck as it makes the right query and you don't have to use any ruby. Besides it won't have to instantiate a Hotel object for each record returned from the DB. (way faster).

Hotel.where(selection: 1).pluck(:id)
# SELECT hotels.id FROM hotels WHERE hotels.selection = 1
# => [2, 3]
like image 27
esbanarango Avatar answered Sep 20 '22 00:09

esbanarango