---
title: "accessed_fields to find active fields in application"
description:
  "Rails 5 introduces accessed_fields method to determine all the fields that
  were accessed on a model while performing some operation"
canonical_url: "https://www.bigbinary.com/blog/accesssed-fields-to-find-actually-used-fileds-in-Rails-5"
markdown_url: "https://www.bigbinary.com/blog/accesssed-fields-to-find-actually-used-fileds-in-Rails-5.md"
---

# accessed_fields to find active fields in application

Rails 5 introduces accessed_fields method to determine all the fields that were
accessed on a model while performing some operation

- Author: Abhishek Jain
- Published: April 18, 2016
- Categories: Rails 5, Rails

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

```ruby
@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](https://github.com/rails/rails/commit/be9b68038e83a617eb38c26147659162e4ac3d2c)
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.

```ruby

class UsersController < ApplicationController
  def index
    @users = User.all
  end
end

```

```erb

# 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.

```ruby

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.

```plaintext

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.

```ruby

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

```

## Links

- [Human page](https://www.bigbinary.com/blog/accesssed-fields-to-find-actually-used-fileds-in-Rails-5)
