accessed_fields to find active fields in application

Abhishek Jain

By Abhishek Jain

on April 18, 2016

This blog is part of our  Rails 5 series.

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

1@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.

1
2class UsersController < ApplicationController
3  def index
4    @users = User.all
5  end
6end
7
1
2# app/views/users/index.html.erb
3
4<table>
5  <tr>
6    <th>Name</th>
7    <th>Email</th>
8  </tr>
9  <% @users.each do |user| %>
10    <tr>
11      <td><%= user.name %></td>
12      <td><%= user.email %></td>
13    </tr>
14  <% end %>
15
16</table>
17

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

1
2class UsersController < ApplicationController
3
4  after_action :print_accessed_fields
5
6  def index
7    @users = User.all
8  end
9
10  private
11
12  def print_accessed_fields
13    p @users.first.accessed_fields
14  end
15end
16

Let's take a look at the log file.

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

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.

1
2class UsersController < ApplicationController
3  def index
4    @users = User.select(:name, :email)
5  end
6end
7