How to protect attributes from being updated?

Hi!
I’m new to Rails!
Rails rox!

1 quesion so far:
I have :email attribute in User model.
I dont’ want :email to allow to be updated.

How do i do this with Rails?
Do I have to implement required validation manually?

Thanks!

On 1/26/07, gmarik [email protected] wrote:

Do I have to implement required validation manually?

Thanks!

classs User < ActiveRecord::Base
attr_protected :email

end

Docs: http://caboo.se/doc/classes/ActiveRecord/Base.html#M006884


Zack C.
http://depixelate.com

Thanks Zak, but it’s not what i need.
I don’t want it to be UPDATED(ie Edit)
And i need this attribute, when object is being CREATED(ie New).

So it could look like this(the code isnt’ valid):

attr_accessible :name, :description
attr_accessible :email if new_record?

Any ideas?
Thanks!

I’d say you should do something like…

attr_accessor :address
attr_protected :email

def before_create
self.email = address
end

and use User#address in the form.

RSL

Nice trick!
Thanks Russell!

On 1/29/07, gmarik [email protected] wrote:

Thanks Zak, but it’s not what i need.
I don’t want it to be UPDATED(ie Edit)
And i need this attribute, when object is being CREATED(ie New).

So it could look like this(the code isnt’ valid):

attr_accessible :name, :description
attr_accessible :email if new_record?

attr_readonly – see http://dev.rubyonrails.org/ticket/6896 – may
be what you’re looking for? I’m not overly optimistic about our
chances of getting it added, though…

Another option for emulating read only attributes could be a
before_save callback that; locks the row (select for update), then
load the model into some variable and then copy the field in question
into self.

I’m not sure Russel’s approach will work; say you load the model, the
row/column is changed by some other process, and then you save your
old model again overwriting the new value.

I’d just go with attr_protected and set that field individually on
creation, if this is all you need.

Isak

Well, for now Russel’s approach is just fine.

The issue with other processes modifying attribute directly can be
avoided by putting attr_reader for :email, so it’ won’t be changed
from outside. Right?

Thanks!

On 1/31/07, gmarik [email protected] wrote:

Well, for now Russel’s approach is just fine.

The issue with other processes modifying attribute directly can be
avoided by putting attr_reader for :email, so it’ won’t be changed
from outside. Right?

If your app is the only thing writing to that particular field,
protecting the attribute in your model - either with attr_protected,
an overridden mutator, or the dummy attribute idea - is probably
enough, yea.

Isak