2010-01-27 31 views
6

如comment_controller.rb看出:SQL注入預防在軌道控制器創建方法

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

林假設這是SQL注入不安全。但是,這樣做的正確方法是什麼?所有在網絡上處理的例子都會發現。

回答

7

該代碼安全的SQL注入攻擊。轉義是由ActiveRecord完成的,所以無論何時您調用模型的find,create,new/save或任何其他數據庫交互方法,您都可以。唯一的例外是,如果你使用原始SQL的選項之一,例如:

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

首選的形式是:

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

這將防止SQL注入自動受到保護。

4

請注意,您的代碼示例從SQL注入安全,如Alex所解釋的,但從mass assignment exploits不安全。

+0

很好的一點 - 不知道爲什麼這之前沒有發生過我 – DanSingerman 2010-01-27 13:51:19