You are familiar with ActiveRecord and its myriad of ways to compose queries. You are cautious of premature optimization, but you know that in rare circumstances, like querying large datasets, instantiating vast amounts of ActiveRecord objects can be taxing for the interpreter (as demonstrated by the benchmarks that you have run against your code).
In those cases you know that you should take advantage of
pluck to extract
only the essential data, without instantiating any models.
In rare cases, when there is no
ActiveRecord::Relation to send
or when raw SQL is the only viable solution 1, a different approach might
be needed. That’s when the
select_* family of methods 2, available on the
ActiveRecord::Base.connection object, comes handy. Its members are:
Each is useful depending on how many columns are being queried and how many rows of results are expected, but honestly, their names are not that intuitive to remember. This is where this cheat sheet comes in.
Given the following table:
The data can be queried in the following ways:
|Returns Single Row||Returns Multiple Rows|
select_all, instead of a raw data structure, an instance of
ActiveRecord::Result is returned. It responds to
but most importantly it is enumerable and as such it can be used as a simple
array of hashes.
Check out the code that generated the examples in the above tables.