Back to Blog

Rails 6.1 adds values_at attribute method for Active Record

This blog is part of our Rails 6.1 series.

Rails 6.1 simplifies retrieving values of attributes on the Active Record model instance by adding the values_at attribute method. This is similar to the values_at method in Hash and Array.

Let's check out an example of extracting values from a User model instance.

2class User < ApplicationRecord
3  def full_name
4    "#{self.first_name} #{self.last_name}"
5  end
8 >> user = 'Era', last_name: 'Das' , email: '')
10=> User id: nil, first_name: "Era", last_name: "Das", created_at: nil, updated_at: nil, email: "", password_digest: nil

Before Rails 6.1

As shown below using values_at for full_name, which is a method, returns nil.

1>> user.attributes.values_at("first_name", "full_name")
2=> ["Era", nil]

After changes in Rails 6.1

Rails 6.1 added the values_at method on Active Record which returns an array containing the values associated with the given methods.

1>> user.values_at("first_name", "full_name")
2=> ["Era", "Era Das"]

Check out the pull request for more details.