简体   繁体   English

Rails Active Record - 从关系中获取 ids 数组

[英]Rails Active Record - Get ids array from relation

I'm looking for an easy/fast way of getting an array of ids from a Active Record relation.我正在寻找一种从 Active Record 关系中获取 id 数组的简单/快速方法。

Currently i have:目前我有:

product_ids = Product.select(:id).where(:colour => 'blue').all.map{|p|p.id}

But that's messy and requires a map..但这很乱,需要地图..

Something like this would be cooler:像这样的东西会更酷:

product_ids = Product.where(:colour => 'blue').ids

Any ideas?有任何想法吗?

Thanks :)谢谢 :)

A little bit more neat solution:更简洁的解决方案:

Product.where(:colour => 'blue').pluck(:id)

In recent versions of Rails the ids method can be used.在最新版本的 Rails 中,可以使用ids方法。

Product.where(color: 'blue').ids

Have been reading through the rails 4 docs and it looks like they support the ids method that I said would be cool in the question now.一直在阅读 rails 4 文档,看起来他们支持ids方法,我说现在在问题中会很酷。

http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-ids http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-ids

Nice to know the team are reading my mind :)很高兴知道团队正在读我的想法:)

To build on the previous answers, if you are working through an association, you can just append _ids to the query.为了建立在前面的答案的基础上,如果您正在处理关联,则只需将_ids附加到查询。

So in your example, if a Supplier has_many Products , then:因此,在您的示例中,如果Supplier has_many Products ,则:

supplier.product_ids

would return your array of product ids that belongs to the supplier.将返回属于供应商的产品 ID 数组。

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

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