19
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Last updated at Posted at 2021-02-26

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])}%") 

参考

19
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?