'Search Fullname, in two fields firstname, lastname rails

I'm working a search box for my application i have two fields firstname and lastname. I create a full_name method for them.

Profile model:

def full_name
"#{self.firstname} #{self.lastname}"
end

and this is my method for search

def self.search_by_full_name(search)
where("(fisrtname || lastname) LIKE :q", :q => "%#{search}%")
end

Profile Controller:

def index
 if params[:search]
  @profile = Profile.search_by_full_name(params[:search])
  else
  @profile = Profile.all
end

end



Solution 1:[1]

Do this simple trick

   def self.search_by_full_name(search)
   @names = search.split(" ")
   where("first_name LIKE ? AND last_name LIKE ?", "%#{@names[0]}","%#{@names[1]}" )
end

Solution 2:[2]

You can do it as

where("CONCAT_WS(' ', first_name, last_name) LIKE ?", "%#{query}%")

or you can create a scope

scope :search_by_full_name ->(query) { where("CONCAT_WS(' ', first_name, last_name) LIKE ?", "%#{query}%") }

Solution 3:[3]

I was stuck with the same problem, So, In order to cover every case scenario.

The best solution for this situation is below

where("CONCAT(first_name,' ',last_name) iLIKE ? OR CONCAT(last_name,' ',first_name ) iLIKE ?", "%#{query}%", "%#{query}%")

P.S. Make sure you apply the squish method on your query first query = search.squish

Solution 4:[4]

My suggestions and its closer to what you have

def self.search_by_full_name(search)
    where("fisrtname LIKE :search OR lastname LIKE :search", search: "%#{search}%")
end

This works for me well. i use sqlite

Solution 5:[5]

Your query is slightly wrong:

def self.search_by_full_name(search)
  where("firstname like :search OR lastname like :search", search: "%#{search}%")
end

Solution 6:[6]

You can do this

User.where("first_name||' '||last_name ilike :name", :name => "%first_name last_name%")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pradeep Sapkota
Solution 2 Fakhir Shad
Solution 3
Solution 4 mrvncaragay
Solution 5 Dylan Knowles
Solution 6 waleednazar