37

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

2
  • 5
    Pluck is the best solution here but just as a btw: instead of map{|p| p.id} can you write map(&:id). This is true for all enumerators (each, any?, select, reject etc.), and will call the symbol on each object it loops through. Commented Jun 14, 2013 at 8:06
  • oh yeah, i knew about map(&:id) just had a mental blank when writing this up :P Commented Jun 14, 2013 at 8:10

3 Answers 3

80

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
Sign up to request clarification or add additional context in comments.

Comments

15

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

Comments

14

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.