简体   繁体   中英

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

What about trying hotels.map(&:id) or hotels.map{|h| h.id } 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.

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]

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

你也可以只拉出id。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM