mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 23:28:02 +00:00
Add Write Safer Where Clauses With Placeholders as a rails til
This commit is contained in:
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
|||||||
For a steady stream of TILs from a variety of rocketeers, checkout
|
For a steady stream of TILs from a variety of rocketeers, checkout
|
||||||
[til.hashrocket.com](https://til.hashrocket.com/).
|
[til.hashrocket.com](https://til.hashrocket.com/).
|
||||||
|
|
||||||
_858 TILs and counting..._
|
_859 TILs and counting..._
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -541,6 +541,7 @@ _858 TILs and counting..._
|
|||||||
- [Truncate Almost All Tables](rails/truncate-almost-all-tables.md)
|
- [Truncate Almost All Tables](rails/truncate-almost-all-tables.md)
|
||||||
- [Update Column Versus Update Attribute](rails/update-column-versus-update-attribute.md)
|
- [Update Column Versus Update Attribute](rails/update-column-versus-update-attribute.md)
|
||||||
- [Where Am I In The Partial Iteration?](rails/where-am-i-in-the-partial-iteration.md)
|
- [Where Am I In The Partial Iteration?](rails/where-am-i-in-the-partial-iteration.md)
|
||||||
|
- [Write Safer Where Clauses With Placeholders](rails/write-safer-where-clauses-with-placeholders.md)
|
||||||
|
|
||||||
### React
|
### React
|
||||||
|
|
||||||
|
|||||||
35
rails/write-safer-where-clauses-with-placeholders.md
Normal file
35
rails/write-safer-where-clauses-with-placeholders.md
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
# Write Safer Where Clauses With Placeholders
|
||||||
|
|
||||||
|
Ruby has a super ergonomic syntax for string interpolation. This can make it
|
||||||
|
tempting to build up ActiveRecord `where` clauses like so:
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
def get_book_by_title(title)
|
||||||
|
Book.where("lower(title) = #{title.downcase}")
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
The `where` clause, as written, is vulnerable to a SQL injection attack.
|
||||||
|
|
||||||
|
There are two kinds of placeholder syntax that you can use instead handle
|
||||||
|
sanitization of the SQL.
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
def get_book_by_title(title)
|
||||||
|
Book.where("lower(title) = ?", title.downcase)
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
You can use multiple `?` in the query and they same number of following
|
||||||
|
arguments will be interpolated in order.
|
||||||
|
|
||||||
|
There is also the keyword placeholder syntax which can give you more
|
||||||
|
flexibility and make the SQL read more clearly.
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
def get_book_by_title(title)
|
||||||
|
Book.where("lower(title) = :title", title: title.downcase)
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
[source](https://devdocs.io/rails~5.2/activerecord/querymethods#method-i-where)
|
||||||
Reference in New Issue
Block a user