I am using Ruby on Rails 3 and I would like to know some behaviours of this code:
@user.send :attributes=, @attrib, false
That is from here.
If I have a form that return these parameters to my controller:
params[:name]
params[:surname]
params[:email]
and in the controller I use
@user.send( # Avoiding 'attr_accessible'
:attributes=, {
:name => params[:name],
:surname => params[:surname] },
false )
@user.save
it should save only ‘name’ and ‘surname’ attributes for the @user ActiveRecord. I tryed that, and it works as expected. But…
1. is it possible that a malicious user can set the email value in someway on the saving process (also if the email attribute is not considered in the “send” statement)?
2. is it right the following statement?
Calling attributes= with false doesn’t
update anything yet, it just sets the
attribute values while ignoring any
attr_accessible whitelist.So you can just call save afterwards,
which returns the boolean value you’re
looking for.
Your code will definitely not allow a malicious user to set the email. I would recommend using the following code though, since it performs the same thing and is easier to read:
Also, passing true as the second parameter to attributes= allows you to protect your attributes using attr_protected and attr_accessible. You can view the documentation here. That means your statement is correct: passing false as the second attribute ignores your mass-assignment protected attributes.