Last active
December 17, 2017 11:00
-
-
Save StevenJL/24af7559264dbd28a7802eeef3b2b0e7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Suppose we load all user records, instantiate them as `User` objects | |
# only to select one attribute. This is wasteful since we select all | |
# columns from the database and load them all into memory. | |
user_emails = User.where(status: "active").map(&:email) | |
# SELECT * FROM users; | |
# Instead, we can use `pluck` to modify the query to select only the | |
# column(s) we need. It also returns the attributes as an array of strings | |
# instead of `User` objects, reducing memory use. | |
user_emails = User.where(status: "active").pluck(:email) | |
# Select users.email FROM users; | |
# If an `ActiveRecord_Relation` of `User` objects is still needed, | |
# then use `select`. This returns the result as an `ActiveRecord_Relation` | |
# of `User` objects but with only the requested attribute(s) in each object. | |
user_emails = User.where(status: "active").select(:email) | |
# Select users.email FROM users; | |
# Only if you really need ALL the attributes of a model, should you not use | |
# `pluck` or `select`. | |
users = User.where(status: "active") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment