Attr_protected and id

Is it necessarty to protect the autogenerated id of an object from
mass assignment in each model. i.e.do I have to do this:

attr_protected :id

in each model if I don’t want users to be able to override the id of
an object?

Dale

Try it and see for yourself.

ruby script/console

x = YourFavoriteModel.find(:first)
=> your object

x.update_attributes(:id => 2)
=> true

x.id
=> ??

Well, this kind of answers the question. What about for things like
x.attributes(params[:x]), or do they all work in the same way? If I
use

x.id = 3
x.save

it is updated, but if I use

x.update_attributes(:id => 3)

it isn’t updated. How are we to know which update methods work this
way and which don’t (does the parameter denote mass updating) ? The
documentation is kind of deficient here

Assuming they all work in the same way (and we all know how assuming
works out), then the follow up question would be how do you allow id
to be mass updated?

Dale

Ah, thanks Aaron, that does clear things up, but ‘ouch’, not being
able to change the id is a little off-putting. Oh well, I guess
copying it is the way to go.

Dale

Your original post asked if you needed to use attr_protected on id.
Yes you do, but that would be a pain, so rails did it for you.
attr_protected prevents somebody from spoofing a form and messing up
your database.

x.id = 3
x.save

Take another look at this one. When you did x.save it returned false,
right? You changed the id of the in-memory version but the save call
failed and the new id was not written to the database.

I don’t know of any straight-forward way to change an id on a record
outside of creating a new record and copying all the other values
over.

Aaron