# Readonly Attributes in Rails

*Published on April 04, 2023*

Tags: Rails Internals

---


Sometimes, you want to prevent changes to certain attributes on your Active Record models after they are initialized and saved in the database. For example, you'd like to set the users' account number upon registration and want to ensure that it's never updated in the future.

Now you could override the&nbsp;[write\_attribute](https://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Write.html#method-i-write_attribute)&nbsp;method or insert a `before_save` / `before_update` callback to listen for the updates to these attributes, but it’d be nice if there was a Rails-style declarative solution to handle this.

**Turns out, there is!**

Rails provides the&nbsp;`attr_readonly`&nbsp;method to mark some attributes on your Active Record models as readonly, to prevent them from further modification. For example, the following code snippet marks the&nbsp;`account_id`&nbsp;property as readonly on a&nbsp;`User`&nbsp;model.

```ruby
class User < ApplicationRecord
  attr_readonly :account_id
end
```

You can create a new&nbsp;`User`&nbsp;record with the initial value for&nbsp;`account_id`, but Rails won’t let you update its value once it’s saved in the database. If you try to change it, the value will only change in memory, but won’t be persisted in the database on calling&nbsp;`save`.&nbsp;**You can only set the value of a readonly attribute when the object isn't&nbsp;saved in the database.**

## Example Usage

This example, along with the tests that follow, shows how to use readonly attributes.

_Note: Starting version 7.1 and above, Rails will raise an error if you try to modify a readonly attribute (covered in the next section)._

```ruby
class Book < ApplicationRecord
  attr_readonly :title
end

class BookTest < ActiveSupport::TestCase
  test "title is readonly" do
    book = Book.create(title: 'Harry Potter')
    assert_equal 'Harry Potter', book.title

    # Try changing the title
    book.update(title: "Chamber of Secrets")

    # Changed in memory
    assert_equal "Chamber of Secrets", book.title

    # Reload the book from database
    book.reload

    # Change was not persisted in database
    assert_equal "Harry Potter", book.title

    ## Convenience methods
    
    # Get a set of all readonly attributes on the model
    assert_equal ["title"].to_set, Post.readonly_attributes
    
    # Check if an attribute is readonly
    assert Post.readonly_attribute? "title"
  end
end
```

### Latest Rails will Raise an Error!

Until very recently, the updates were getting ignored silently. That meant assignment would succeed but silently not write to the database. However, this behavior was changed a few months ago in this pull request:&nbsp;[Raise on assignment to readonly attributes](https://github.com/rails/rails/pull/46105)

If you try to update a readonly attribute on a model that’s already saved in the database, Rails will raise&nbsp;`ActiveRecord::ReadonlyAttributeError`. Set the `config.active_record.raise_on_assign_to_attr_readonly` setting to&nbsp;`false`&nbsp;to prevent Rails from raising this error.

## How Rails Implements Readonly Attributes

This functionality is defined in the&nbsp;`ActiveRecord::ReadonlyAttributes`&nbsp;module, which is a concern. The&nbsp;`ActiveRecord::Base`&nbsp;class includes it and hence all your Active Record models get this behavior out of the box.

```ruby
# activerecord/lib/active_record/readonly_attributes.rb

module ActiveRecord
  module ReadonlyAttributes
    extend ActiveSupport::Concern
    
  end
end
```

To learn more about how concerns work, check out this article: [Concerns in Rails: Everything You Need to Know](/how-rails-concerns-work-and-how-to-use-them)

This concern defines a&nbsp;[`class_attribute`](https://api.rubyonrails.org/classes/Class.html#method-i-class_attribute)&nbsp;named&nbsp;`_attr_readonly`&nbsp;on your Rails model. By default, it’s set to an empty array.

```ruby
class_attribute :_attr_readonly, instance_accessor: false, default: []
```

The&nbsp;`attr_readonly`&nbsp;method is added as a class method to the Active Record model, such as&nbsp;`User`. That’s why you can call it directly inside the class.

Here’s a simplified implementation of this method.

```ruby
module ClassMethods
  def attr_readonly(*attributes)
    self._attr_readonly |= attributes.map(&:to_s)
  end

  def readonly_attributes
    _attr_readonly
  end

  def readonly_attribute?(name) # :nodoc:
    _attr_readonly.include?(name)
  end
end
```

As you can see, when we mark an attribute as readonly using the&nbsp;`attr_readonly`&nbsp;method, Rails will simply store it in the&nbsp;`_attr_readonly`&nbsp;array, which we saw in the previous snippet.

Later, when the record is saved, Rails will exclude all the attributes in this array from the list of attributes to be saved in the database. See the&nbsp;`ActiveRecord::Associations::CollectionAssociation#merge_target_lists`&nbsp;method to learn more.

> 💡 **Your challenge for the day:**&nbsp;Open the latest Rails source and go to the&nbsp;`readonly_attributes.rb`&nbsp;file. Try to understand the&nbsp;`HasReadonlyAttributes`&nbsp;module and how it works.

## Additional Resources

- [Rails API documentation for&nbsp;`attr_readonly`](https://api.rubyonrails.org/classes/ActiveRecord/ReadonlyAttributes/ClassMethods.html#method-i-attr_readonly)
- [PR #46105: Raise on assignment to readonly attributes](https://github.com/rails/rails/pull/46105)
- [How class attributes work in Rails](https://api.rubyonrails.org/classes/Class.html#method-i-class_attribute)

