Forum: Ruby on Rails Preventing/validating model data changes on update

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
076787da0775e1600ae30ea00f804809?d=identicon&s=25 Nexos (Guest)
on 2007-06-05 10:27
(Received via mailing list)

I have a User model with a "name" attribute (and some others not shown
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

  def before_validation_on_update
    if (name != @original_name)
      errors.add(:name, "User name can't be modified !")


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 = => 'foo')
u.valid? -> true = 'bar'
u.valid? -> true -> true
(initial save) = '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,

076787da0775e1600ae30ea00f804809?d=identicon&s=25 Nexos (Guest)
on 2007-06-05 12:58
(Received via mailing list)

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?

This topic is locked and can not be replied to.