I want to find all widgets with their common or internal names in a certain list query_list. I can do
# Consider query_list = ["a","b","c"]
qlist = '(' + query_list.join(",") + ')'
# this makes
widgets = Widget.find_by_sql("SELECT * FROM widgets
WHERE common_name IN #{qlist} OR internal_name IN #{qlist}")
Now I have a few questions:
- Is the above find_by_sql safe regarding SQL injection attacks? It seems like one could put in something dangerous in
query_list.- How about writing
.find_by_sql(["SELECT * FROM widgets
WHERE common_name IN ? OR internal_name IN ?", ["a","b","c"], ["a","b","c"] ]) - If it isn’t safe, can we make it safe?
- How about writing
- I prefer not to write raw sql if I don’t have to. I know we can write
ANDconditions infind, as in.find(:conditions=>{:internal_name => ['a','b','c'], :common_name => ['a','b','c']}). Can we also writeORconditions using find? - How about using
where? How is this different from usingfind?
The version with placeholders is safe against SQL injection, as long as you don’t mind users being able to select arbitrary widgets, which I assume you don’t. Depending on what version of Rails you have, you can avoid writing raw SQL using chaining; see Ruby on Rails 3 howto make ‘OR’ condition.
Note that your code as is, or with the placeholders, will cause a database error if the list is empty, or is
[nil], so it’s best to test that query_list.first is present before making the query.