Safe ActiveRecord like query

2019-01-07 15:50发布

I'm trying to write LIKE query.

I read that pure string quires aren't safe, however I couldn't find any documentation that explain how to write safe LIKE Hash Query.

Is it possible? Should I manually defend against SQL Injection?

4条回答
再贱就再见
2楼-- · 2019-01-07 16:04

You can do

MyModel.where(["title LIKE ?", "%#{params[:query]}%"])
查看更多
冷血范
3楼-- · 2019-01-07 16:14

For PostgreSQL it will be

Foo.where("bar ILIKE ?", "%#{query}%") 
查看更多
4楼-- · 2019-01-07 16:22

To ensure that your query string gets properly sanitized, use the array or the hash query syntax to describe your conditions:

Foo.where("bar LIKE ?", "%#{query}%")

or:

Foo.where("bar LIKE :query", query: "%#{query}%")

If it is possible that the query might include the % character then you need to sanitize query with sanitize_sql_like first:

Foo.where("bar LIKE ?", "%#{sanitize_sql_like(query)}%")
Foo.where("bar LIKE :query", query: "%#{sanitize_sql_like(query)}%")
查看更多
Evening l夕情丶
5楼-- · 2019-01-07 16:24

Using Arel you can perform this safe and portable query:

title = Model.arel_table[:title]
Model.where(title.matches("%#{query}%"))
查看更多
登录 后发表回答