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
On 5 juin, 10:26, Nexos
<frederic.dela...-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>
wrote:> 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
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---