This blog is part of our Rails 5 series.

Rails makes it very easy to select all the fields of a table.

@users = User.all

Above code is selecting all the columns of the table users. This might be ok in most cases. However in some cases we might want to select only certain columns for performance reason. The difficult task is finding what all columns are actually used in a request.

To help in this task, Rails 5 has added accessed_fields method which lists attributes that were actually used in the operation.

This is helpful in development mode in determining what all fields are really being used by the application.

class UsersController < ApplicationController
  def index
    @users = User.all
  end
end
# app/views/users/index.html.erb

<table>
  <tr>
    <th>Name</th>
    <th>Email</th>
  </tr>
  <% @users.each do |user| %>
    <tr>
      <td><%= user.name %></td>
      <td><%= user.email %></td>
    </tr>
  <% end %>

</table>

Now, in order to find all the fields that were actually used, let’s add after_action to the controller.

class UsersController < ApplicationController

  after_action :print_accessed_fields

  def index
    @users = User.all
  end

  private

  def print_accessed_fields
    p @users.first.accessed_fields
  end
end

Let’s take a look at the log file.

Processing by UsersController#index as HTML
  User Load (0.1ms) SELECT "users".* FROM "users"
  Rendered users/index.html.erb within layouts/application (1.0ms)
  ["name", "email"]

As we can see, it returns ["name", "email"] as attributes which were actually used.

If users table has 20 columns then we do not need to load values all those other columns. We are using only two columns. So let’s change code to reflect that.

class UsersController < ApplicationController
  def index
    @users = User.select(:name, :email)
  end
end