One minute
Optimizing database queries using pluck 📝
Instead of using the all
method, which loads all records into memory, use the pluck
method to retrieve specific columns from the database.
For example, if you only need to retrieve the names/emails of all users, you can use the following code:
# Using pluck instead of all
❯ user_names = User.pluck(:name)
❯ user_emails = User.pluck(:email)
This will return an array of names and emails, which is more memory efficient than loading all of the user records into memory.
Read other posts
comments powered by Disqus