Rails ActiveRecord - Search on Multiple Attributes Rails ActiveRecord - Search on Multiple Attributes ruby-on-rails ruby-on-rails

Rails ActiveRecord - Search on Multiple Attributes


I assumed your model name is Model - just replace it with your real model name when you do the actual query:

Model.where("name LIKE ? OR last_name LIKE ? OR first_name LIKE ?", "%#{search}%","%#{search}%","%#{search}%")

About your worries about SQL injections - both of code snippets are immune to SQL injections. As long as you do not directly embed strings into your WHERE clause you are fine. An example for injection-prone code would be:

Model.where("name LIKE '#{params[:name]}'")


Although the selected answer will work, I noticed that it breaks if you try to type a search "Raul Riera" because it will fail on both cases, because Raul Riera is not either my first name or my last name.. is my first and last name... I solved it by doing

Model.where("lower(first_name || ' ' || last_name) LIKE ?", "%#{search.downcase}%")


With Arel, you can avoid writing the SQL manually with something like this:

Model.where(  %i(name first_name last_name)    .map { |field| Model.arel_table[field].matches("%#{query}%")}    .inject(:or))

This would be particularly useful if the list of fields to match against was dynamic.