开发者

Get all ids from a collection

开发者 https://www.devze.com 2023-04-10 22:25 出处:网络
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 :

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 }?

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


You can also pull just the id's.

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

精彩评论

暂无评论...
验证码 换一张
取 消