Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Use .pluck If You Only Need a Subset of Model Attributes

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 154
    Comment on it

    If you want few attributes from a table, instead of instantiating a collection of models and then running a .map over them to get the data you need, its very much economical to use .pluck to pull only the attributes you need as a array.

    There would be two benefits in this:

    1) SQL performance would be much better

    2) Less time and memory would be spent.

    Let's take an example as a ruby code:

    users = User.all.map { |u| u.email }
    
    users = User.pluck(:email)
    

    So in the case we are using .pluck it would be very much efficient in terms of performance, time and memory.

    We can use .pluck across the tables as well. So in first case we saw that we have plucked emails and now we need an array of two-element arrays consisting of the email and the users address, stored in the users table. Our approach then becomes:

    users = User.all.map { |u| [u.email, u.user_profile.address]
    
    users = User.includes(:user_education).pluck(:email, :address)
    

    Prefering .pluck to instantiating a collection of ActiveRecord objects and then using .map to build an array of attributes.

    .pluck can do more than simply pull attributes on a single table: it can also run SQL functions, pull attributes from joined tables, and shift on to any scope.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: