Just a quick look at
select in Rails.
Lets say we have a
User with an active and a balance field on him.
active field is a boolean and the
balance field is float.
Now, we want to select the balance of all our active users.
We can of course do this in several ways.
We start by defining a scope for finding the active users:
Now we can grab all active users with:
We want to find each their balance, so something like this might come natural to most:
The SQL generated here will actually be:
This means that we will grab every field on the
User model and instantiate that object, and then, with
.map(&:balance) grab the balance from each object.
We want to do all this in the SQL, as we are just tossing all the other data, we do not need to actually fetch it from the database. We could do something like this, to not get all the unneeded fields:
This will generate this SQL instead:
and then only provide us with dummy
User objects with the balances.
Mapping over these, will yield the exact same result as above, however this time, we do not have to toss any data as we only fetch the balances.
Oh, but we mentioned
balance twice in the above ruby code.
That’s not very nice, can’t we have some sugar for that?
Well, of course we can.
pluck to the rescue.
To do a combined
map we can do:
which yield the exact same SQL:
We’ll end up with an array of balances, but this time we only had to tell it once about the
Conclusion: Always use
pluck in favour of
select and then