ruby on rails does update_attributes protect against sql injection?
Does update_attri开发者_运维技巧butes protect against sql injection?
Example:
if @user.update_attributes(params[:user])
# updated
end
I know find(), and {} and [] do in find :conditions, but didn't see any info on this method.
Yes, it does. Internally, it simply loops over all attributes, set their values then invoke save!
def update_attributes(attributes)
with_transaction_returning_status do
self.attributes = attributes
save
end
end
def attributes=(new_attributes, guard_protected_attributes = true)
...
attributes.each do |k, v|
if k.include?("(")
multi_parameter_attributes << [ k, v ]
elsif respond_to?("#{k}=")
send("#{k}=", v)
else
raise(UnknownAttributeError, "unknown attribute: #{k}")
end
end
end
In other words, what it does is
m.update_attributes(:attr1 => "foo", :attr2 => "bar")
m.attr1 = "foo"
m.attr2 = "bar"
m.save
All activerecord methods in Rails3 that interact with the database are safe from sql injection.
The only exception is if you use raw SQL for one of the options, for example:
Comment.find(:all, :conditions => "user_id = #{params[:user]}")
the preferred form is:
Comment.find(:all, :conditions => {:user_id => params[:user})
which will be automatically protected against SQL injection.
精彩评论