# Preventing/validating model data changes on update

**URL:** <https://www.ruby-forum.com/t/preventing-validating-model-data-changes-on-update/105983>\
**Category:** Rails\
**Created:** [June 5, 2007, 10:27am UTC](https://www.ruby-forum.com/t/preventing-validating-model-data-changes-on-update/105983 "2007-06-05T10:27:53Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Nexos](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/df705f/32.png) [@Nexos](https://www.ruby-forum.com/u/Nexos)\
**Post date:** [June 5, 2007, 10:27am UTC](https://www.ruby-forum.com/t/preventing-validating-model-data-changes-on-update/105983/1 "2007-06-05T10:27:53Z")

</div>

Hi,

I have a User model with a “name” attribute (and some others not shown  
here).  
I’d like to prevent name modification after the initial creation in  
the DB.  
Here is the code I used:

class User \< ActiveRecord::Base

validates\_presence\_of :name  
validates\_uniqueness\_of :name

def after\_initialize  
@original\_name = name  
end

def before\_validation\_on\_update  
if (name != @original\_name)  
errors.add(:name, “User name can’t be modified !”)  
end  
end

end

The problem is @original\_name is well correctly set on user update,  
but can still be modified and save at any time.

Specifically, what I tried in a console is:  
u = User.new(:name =\> ‘foo’)  
u.valid? -\> true  
u.name = ‘bar’  
u.valid? -\> true  
u.save -\> true  
(initial save)

u.name = ‘baz’  
u.valid? -\> true ===\> should be false !

I know I could simply avoid to place the field in the views, but I  
want to enforce this in the model.

Any suggestion ?

Thanks in advance,

Frédéric

---

<div class="post-metadata">

**Author:** ![Nexos](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/df705f/32.png) [@Nexos](https://www.ruby-forum.com/u/Nexos)\
**Post date:** [June 5, 2007, 12:58pm UTC](https://www.ruby-forum.com/t/preventing-validating-model-data-changes-on-update/105983/2 "2007-06-05T12:58:29Z")

</div>

Hey,

I found the solution.  
The problem was I didn’t use “return false” after using  
“errors.add(:name, “User name can’t be modified !”)”.

I simply thought the very fact of adding errors would make valid?  
false.

Frédéric
