Ruby-on-rails Rails Active Record - 从关系中获取 ids 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17103003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails Active Record - Get ids array from relation
提问by complistic
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 :)
谢谢 :)
回答by megas
A little bit more neat solution:
更简洁的解决方案:
Product.where(:colour => 'blue').pluck(:id)
回答by complistic
Have been reading through the rails 4 docs and it looks like they support the idsmethod 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 :)
很高兴知道团队正在读我的想法:)
回答by Hyman Collins
To build on the previous answers, if you are working through an association, you can just append _idsto the query.
为了建立在以前的答案的基础上,如果您正在处理关联,则可以附加_ids到查询中。
So in your example, if a Supplierhas_manyProducts, then:
所以在你的例子中,如果 a Supplierhas_manyProducts,那么:
supplier.product_ids
would return your array of product ids that belongs to the supplier.
将返回属于供应商的产品 ID 数组。

