开发者

sql injection prevention for create method in rails controller

As seen in comment_controller.rb:

def create
    @comment = Comment.new(params[:comment])
    @comment.save
end

Im assu开发者_高级运维ming that this is SQL injection-unsafe. But what is the correct way of doing it?.. All the examples on the net deal with finds.


That code is safe from SQL injection attacks. The escaping is done by ActiveRecord, so any time you call a model's find, create, new/save, or any other method that does database interaction, you're OK. The only exception is if you use raw SQL for one of the options, for example:

Comment.find(:all, :conditions => "user_id = #{params[:user_id]}")

the preferred form is:

Comment.find(:all, :conditions => {:user_id => params[:user_id]})

which will be automatically protected against SQL injection.


Note that your code example is safe from SQL injection as explained by Alex, but it's not safe from mass assignment exploits.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜