5
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

RailsのSQLインジェクション対策まとめ

find、find_by

普通に使っている分にはSQLインジェクションは発生しないのであまり気にする必要なし。

(参考)
ActiveRecord::Base#find is SQL injection free? - Rails - Ruby-Forum

シンプルなwhere句

#  NG
User.where("name='#{params[:name]}'")
# OK
User.where(name: params[:name])
User.where("name = ?", params[:name])

複数条件で検索

# NG
User.where("name = #{params[:name]} or age < #{params[:age]}")

# OK
User.where("name = ? or age < ?", params[:name], params[:age])

Likeを使ったあいまい検索

# NG
User.where('name LIKE ?', "%#{params[:name]}%") 

# OK
User.where('name LIKE ?', "%#{sanitize_sql_like(params[:name])}%") 

参考

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
5
Help us understand the problem. What are the problem?