Preventing/validating model data changes on update

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

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs