Reputation: 5929
Would like to build rails active record query with multiple optional where conditions.
Example:
I have a patient search form that able to search by id, name and email address. The pseudo code would be as below:
where_sql = ""
where_sql = {'name = ?", params[:name]} if params[:name]
where_sql = {'id = ?", params[:id]} if params[:id]
where_sql = {'email = ?", params[:email]} if params[:email]
Patient.where(where_sql)
How do I build following queries without worrying about sql injection.
Upvotes: 1
Views: 850
Reputation: 23770
If you use questionmark "?" placeholders or hashes ActiveRecord automatically escapes the values for you. See injection countermeasures in rails guides http://guides.rubyonrails.org/security.html#sql-injection
This might be a nice use case for the ransack gem (MetaWhere rewrite) https://github.com/ernie/ransack
Upvotes: 1
Reputation: 5832
If you are using only equal conditions, you can do it like:
conditions = {}
conditions[:name] = params[:name] if params[:name]
conditions[:id] = params[:id] if params[:id]
conditions[:email] = params[:email] if params[:email]
Patient.where(conditions)
Also, take a look to a great searchlogic gem.
Upvotes: 0