# Prevent attribute from being changed with "attr\_readonly"

**URL:** <https://www.ruby-forum.com/t/prevent-attribute-from-being-changed-with-attr-readonly/171463>\
**Category:** Rails\
**Created:** [July 2, 2009, 10:19pm UTC](https://www.ruby-forum.com/t/prevent-attribute-from-being-changed-with-attr-readonly/171463 "2009-07-02T22:19:18Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Learn\_by\_D](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/e274bd/32.png) [@Learn\_by\_D](https://www.ruby-forum.com/u/Learn_by_D)\
**Post date:** [July 2, 2009, 10:19pm UTC](https://www.ruby-forum.com/t/prevent-attribute-from-being-changed-with-attr-readonly/171463/1 "2009-07-02T22:19:18Z")

</div>

Is there a way to prevent an attribute from being changed from outside  
the class instance? So that after a record is created, the attribute can  
be read but cannot be changed from outside the class instance.

At first glance, “attr\_readonly” seems to be the solution. However,  
will “attr\_readonly” also prevent the attribute from being changed even  
from inside the class?

In other words, will the following method successfully change the values  
of attribute\_a and attribute\_b in model A?

1.Class A \< ActiveRecord::Base  
2. attr\_readonly :attribute\_a, :attribute\_b  
3. def change\_attributes(new\_a, new\_b)  
4. self.attribute\_a = new\_a  
5. self.attribute\_b = new\_b  
6. save!  
7. end  
8. end

I know I can redefine the write accessor if I want to customize the way  
a single attribute is changed. However here I would like to change two  
attributes in one transaction and prevent each attribute from being  
changed individually.

Thanks

* * *

Developing with Rails 2.3.2; Ruby 1.8.7 (2009-04-08 patchlevel 160)  
[powerpc-darwin9]

---

<div class="post-metadata">

**Author:** ![Learn\_by\_D](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/e274bd/32.png) [@Learn\_by\_D](https://www.ruby-forum.com/u/Learn_by_D)\
**Post date:** [July 3, 2009, 9:53am UTC](https://www.ruby-forum.com/t/prevent-attribute-from-being-changed-with-attr-readonly/171463/2 "2009-07-03T09:53:57Z")

</div>

I tried to make private the write accessor for an attribute (e.g., foo)  
that I want to protect by defining:

Code : - fold - unfold

1. def foo=val
2. super
3. end

However, when I make the write accessor private, I cannot even call it  
from inside the class because a statement such as self.foo = val returns  
NoMethodError: Attempt to call private method  
Please help. Thanks.
