ActiveRecord (SQL) query multiple columns only if search string not empty

Viewed 214

Using a PG database filled with registered voters.

Trying to set it up so I can search by first name, last name, zip or city. I want to be able to find all voters that match all of the entered params, but having trouble dealing with empty search fields.

where("zip LIKE ? OR city LIKE ? OR last_name LIKE ? OR first_name LIKE ?",
 "#{params[:zip]}","#{params[:city]}","#{params[:last_name]}","#{params[:first_name]}")

Is there a better way to build it out so that it matches ALL entered parameters, but ignores empty string parameters? Right now if I enter a first and last name 'John Smith' I will get 'John Jones' and 'Jane Smith'.

1 Answers
Related