简体   繁体   English

从集合中获取所有ID

[英]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? 如何在没有循环的情况下获取此项目的所有ID? Can i use something like : 我可以使用类似的东西:

hotels.ids ? 

Thank you 谢谢

What about trying hotels.map(&:id) or hotels.map{|h| h.id } 那么尝试hotels.map(&:id)hotels.map{|h| h.id } 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. 它们对Ruby来说意味着同样的东西,第一个通常更适合习惯的红宝石,而第二个更容易为初学者理解。

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. 如果你只需要一个包含所有ID的数组,你应该使用pluck,因为它可以进行正确的查询,而且你不必使用任何ruby。 Besides it won't have to instantiate a Hotel object for each record returned from the DB. 此外,它不必为从DB返回的每条记录实例化一个Hotel对象。 (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: 如果您使用Rails> 4,则可以使用ids方法:

Person.ids  # SELECT people.id from people

More info: http://apidock.com/rails/ActiveRecord/Calculations/ids 更多信息: http//apidock.com/rails/ActiveRecord/Calculations/ids

你也可以只拉出id。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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