Last Updated: February 25, 2016
·
317
· amydoesntlai

Avoiding repeated query variables

If you find yourself wanting to dry up a query like this:

Book.where('title = ? OR author = ? OR genre = ? OR subject = ? OR keyword = ?', search_term, search_term, search_term, search_term, search_term)

use named bind variables:

Book.where('title = :s OR author = :s OR genre = :s OR subject = :s OR keyword = :s', {s: search_term})

More on this:

http://madebydna.com/all/code/2010/11/08/active-record-named-bind-variables.html

http://millarian.com/programming/ruby-on-rails/quick-tip-rails-named-bind-variables/