Skip to content

Instantly share code, notes, and snippets.

@amitpatelx
Last active January 9, 2020 20:59
Show Gist options
  • Save amitpatelx/c89258fd721de0b5497a to your computer and use it in GitHub Desktop.
Save amitpatelx/c89258fd721de0b5497a to your computer and use it in GitHub Desktop.
map vs pluck - Getting value of specific column using ActiveRecord

map will load the entire array, then iterate to collect the screen_names.

pluck asks the database for exactly what it needs and returns an array of just those items.

So in case of pluck, performance is gained and less memory is used for large datasets (like production).

Never use map on active record relations, use pluck instead.

If you're using pluck to pass values to a where use select instead

User.where(screen_name: users.select(:screen_name)).empty?

CAUTION:

http://6ftdan.com/allyourdev/2015/05/13/rails-dont-pluck-unnecessarily/

Reference:

http://hashrocket.com/blog/posts/rails-quick-tips-easy-activerecord-optimizations

# Using `map?`
User.where(email: ['jane@example.com', 'john@example.com']).map(&:screen_name)
# 1. Queries database for all user data
# SELECT "users".* FROM "users" WHERE "users"."email" IN ('jane@example.com','john@example.com')
# 2. Loads users into an array
# [<#User:0x007fbf6413c510>,<#User:0x007fbf65ab1c70>]
# 3. Iterates over users to collect screen_names
# ['user1','user2']
# Using `pluck?`
User.where(email: ['jane@example.com', 'john@example.com']).pluck(:screen_name)
# 1. Queries database for only screen_names
# SELECT "users"."screen_name" FROM "users" WHERE "users"."email" IN ('jane@example.com','john@example.com')
# 2. Returns those screen_names in an array
# ['user1','user2']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment