Sebastien
Sebastien

Reputation: 6660

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

Upvotes: 20

Views: 23294

Answers (5)

Jeff Spicoli
Jeff Spicoli

Reputation: 500

Rails 6+ has added something called extract_associated docs | blog

Where the association (has_many) of a collection/list can be queried.

Example, a Company has many hotels and each hotel has_many managers, to get all the hotel managers associated user id:

hotels = Company.hotels.active
hotels.extract_associated(:mangers).flatten.pluck(:user_id)

Upvotes: 0

rizidoro
rizidoro

Reputation: 13418

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

Person.ids  # SELECT people.id from people

More info: http://apidock.com/rails/ActiveRecord/Calculations/ids

Upvotes: 16

esbanarango
esbanarango

Reputation: 1637

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]

Upvotes: 28

David Nehme
David Nehme

Reputation: 21572

You can also pull just the id's.

hotels.select(:id).where(selection: 1)

Upvotes: 10

Romain
Romain

Reputation: 12809

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.

Upvotes: 30

Related Questions