Forum: Ruby on Rails attr_protected and id

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
9ae68be4f6aff5c6aa7a0eb7087251e9?d=identicon&s=25 PeteSalty (Guest)
on 2007-02-08 23:27
(Received via mailing list)
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
8da92d4ed91aa12535f6d870fa76b25e?d=identicon&s=25 Aaron (Guest)
on 2007-02-08 23:46
(Received via mailing list)
Try it and see for yourself.

ruby script/console

>> x = YourFavoriteModel.find(:first)
=> your object
>> x.update_attributes(:id => 2)
=> true
>> x.id
=> ??
9ae68be4f6aff5c6aa7a0eb7087251e9?d=identicon&s=25 PeteSalty (Guest)
on 2007-02-09 00:09
(Received via mailing list)
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
8da92d4ed91aa12535f6d870fa76b25e?d=identicon&s=25 Aaron (Guest)
on 2007-02-09 00:32
(Received via mailing list)
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
9ae68be4f6aff5c6aa7a0eb7087251e9?d=identicon&s=25 PeteSalty (Guest)
on 2007-02-09 02:54
(Received via mailing list)
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
This topic is locked and can not be replied to.