Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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 :)

like image 552
complistic Avatar asked Jun 14 '13 07:06

complistic


1 Answers

A little bit more neat solution:

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

In recent versions of Rails the ids method can be used.

Product.where(color: 'blue').ids 
like image 197
megas Avatar answered Oct 18 '22 09:10

megas