Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for getting a list of IDs from an ActiveRecord model

I have an ActiveRecord model Language, with columns id and short_code (there are other columns, but they are not relevant to this question). I want to create a method that will be given a list of short codes, and return a list of IDs. I do not care about associations, I just need to end up with an array that looks like [1, 2, 3, ...].

My first thought was to do something like

def get_ids_from_short_codes(*short_codes)
  Language.find_all_by_short_code(short_codes.flatten, :select => 'id').map(&:id)
end

but I'm not sure if that's needlessly wasting time/memory/processing.

My question is twofold:

  1. Is there a way to run an ActiveRecord find that will just return an array of a certain table column rather than instantiating objects?
  2. If so, would it actually be worthwhile to collect an array of length n rather than instantiating n ActiveRecord objects?

Note that for my specific purpose, n would be approximately 200.

like image 372
Daniel Vandersluis Avatar asked Nov 28 '22 15:11

Daniel Vandersluis


2 Answers

In Rails 3.x, you can use the pluck method which returns the values from the requested field without instantiating objects to hold them.

This would give you an array of IDs:

Language.where(short_code: short_codes.flatten).pluck(:id)

I should mention that in Rails 3.x you can pluck only one column at a time but in Rails 4 you can pass multiple columns to pluck.

By the way, here's a similar answer to a similar question

like image 165
antinome Avatar answered Dec 18 '22 20:12

antinome


Honestly, for 200 records, I wouldn't worry about it. When you get to 2000, 20,000, or 200,000 records - then you can worry about optimization.

Make sure you have short_code indexed in your table.

If you are still concerned about performance, take a look at the development.log and see what the database numbers are for that particular call. You can adjust the query and see how it affects performance in the log. This should give you a rough estimate of performance.

like image 28
Phil Avatar answered Dec 18 '22 20:12

Phil