Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord - Search on Multiple Attributes

I'm implementing a simple search function that should check for a string in either the username, last_name and first_name. I've seen this ActiveRecord method on an old RailsCast:

http://railscasts.com/episodes/37-simple-search-form

find(:all, :conditions => ['name LIKE ?', "%#{search}%"])

But how do I make it so that it searches for the keyword in name, last_name and first name and returns the record if the one of the fields matched the term?

I'm also wondering if the code on the RailsCast is prone to SQL injections?

Thanks a lot!

like image 773
gerky Avatar asked Aug 05 '12 13:08

gerky


1 Answers

A more generic solution for searching in all fields of the model would be like this

def search_in_all_fields model, text
  model.where(
    model.column_names
      .map {|field| "#{field} like '%#{text}%'" }
      .join(" or ")
  )
end

Or better as a scope in the model itself

class Model < ActiveRecord::Base
  scope :search_in_all_fields, ->(text){
    where(
      column_names
        .map {|field| "#{field} like '%#{text}%'" }
        .join(" or ")
    )
  }
end

You would just need to call it like this

Model.search_in_all_fields "test"

Before you start.., no, sql injection would probably not work here but still better and shorter

class Model < ActiveRecord::Base
  scope :search_all_fields, ->(text){
    where("#{column_names.join(' || ')} like ?", "%#{text}%")
  }
end
like image 105
peter Avatar answered Oct 24 '22 11:10

peter