complistic
complistic

Reputation: 2710

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

Upvotes: 37

Views: 36722

Answers (3)

megas
megas

Reputation: 21791

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

Upvotes: 80

Jack Collins
Jack Collins

Reputation: 1165

To build on the previous answers, if you are working through an association, you can just append _ids to the query.

So in your example, if a Supplier has_many Products, then:

supplier.product_ids

would return your array of product ids that belongs to the supplier.

Upvotes: 14

complistic
complistic

Reputation: 2710

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.

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

Nice to know the team are reading my mind :)

Upvotes: 15

Related Questions