Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby on rails does update_attributes protect against sql injection?

Does update_attributes 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.

like image 764
djburdick Avatar asked Feb 26 '23 17:02

djburdick


2 Answers

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
like image 188
Simone Carletti Avatar answered Mar 22 '23 22:03

Simone Carletti


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.

like image 29
DanS Avatar answered Mar 23 '23 00:03

DanS