%s
is intended for strings. The main difference is that %s
doesn't add quotes. From ActiveRecord::QueryMethods.where
:
Lastly, you can use sprintf-style % escapes in the template. This works slightly differently than the previous methods; you are responsible for ensuring that the values in the template are properly quoted. The values are passed to the connector for quoting, but the caller is responsible for ensuring they are enclosed in quotes in the resulting SQL. After quoting, the values are inserted using the same escapes as the Ruby core method
Kernel::sprintf
.
Examples:
User.where(["name = ? and email = ?", "Joe", "joe@example.com"])
# SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
User.where(["name = '%s' and email = '%s'", "Joe", "joe@example.com"])
# SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
Update:
You are passing an array. %s
seems to calls .to_s
on the argument so this might not works as expected:
User.where("name IN (%s)", ["foo", "bar"])
# SELECT * FROM users WHERE (name IN ([\"foo\", \"bar\"]))
User.where("name IN (?)", ["foo", "bar"])
# SELECT * FROM users WHERE (name IN ('foo','bar'))
For simple queries you can use the hash notation:
User.where(name: ["foo", "bar"])
# SELECT * FROM users WHERE name IN ('foo', 'bar')