Hello everyone!
I want to have login field in User model which is set only once (on
create), and then it should fail validation if the value is changed.
How can I do this? I dig around for validation and tried
def after_validation_on_update
unless User.find_by_login(:login)
errors.add(:login, “is immutable. You can’t change it”)
end
end
in model, but somewhat it doesn’t work. Any hints on how can I make
field immutable after create?
Peace,
olegf
I’m almost positive there’s a better way, but you could try something
like this in the validate method of your model.
def validate
errors.add( :login, "Can't change your login details") if
self.login != User.find(self.id).login
end
Sorry there should be another line in that method
def validate
if not self.new_record?
errors.add( :login, “Can’t change your login details”) if
self.login != User.find(self.id).login
end
end
Yep, just do:
class User < ActiveRecord::Base
def login=(value)
# Either ignore the call, add an error, or raise an exception
end
end
Can you just override the default setter that active records creates in
your model and throw an execption if it gets called?
What’s an Intel chip doing in a Mac? A whole lor more that it’s ever
done in a PC.
My Digital Life - http://scottwalter.com/blog
Pro:Blog - http://scottwalter.com/problog
Snippets - http://snippets.scottwalter.com
----- Original Message ----
From: Oleg F. [email protected]
To: [email protected]
Sent: Monday, May 8, 2006 12:53:13 AM
Subject: [Rails] how to make field in model immutable after create
Hello everyone!
I want to have login field in User model which is set only once (on
create), and then it should fail validation if the value is changed.
How can I do this? I dig around for validation and tried
def after_validation_on_update
unless User.find_by_login(:login)
errors.add(:login, “is immutable. You can’t change it”)
end
end
in model, but somewhat it doesn’t work. Any hints on how can I make
field immutable after create?
Peace,
olegf
If you make it so that the setter method throws an exception/stops the
call,
how do you set the login when the record is first created?
Something along the lines of…
def login= (value)
if new_record?
self[:login] = value
else
raise “You can’t change login”
end
end