Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using `CONCAT` w/ Arel in Rails 4

I have a User model that has first_name and last_name attributes. Using Arel I would like to perform a full name search using CONCAT. I've read the post at How do I use functions like CONCAT(), etc. in ARel? which gives me indication that this is possible but I can't quite get the syntax right. So far I have

class User < ActiveRecord::Base
  def self.search(query)
    concat = Arel::Nodes::NamedFunction.new 'concat', [arel_table[:first_name], arel_table[:last_name]]
    where ...?
  end
end
like image 501
Kyle Decot Avatar asked Dec 06 '13 19:12

Kyle Decot


2 Answers

With the latest Arel it's required to use Arel::Nodes.build_quoted(' ') instead of just String (' '). So the answer nowadays is:

SEPARATOR = Arel::Nodes.build_quoted(' ')

Arel::Nodes::NamedFunction.new(
  'concat',
  [arel_table[:first_name], SEPARATOR, arel_table[:last_name]]
)
like image 197
sharipov_ru Avatar answered Oct 27 '22 15:10

sharipov_ru


If you want an equal search

 where(concat.eq("john smith"))

 SELECT "users".* FROM "users" WHERE CONCAT("users"."first_name", "users"."last_name") = 'john smith'

If you want a like search

where(concat.matches("%john smith%"))

 SELECT "users".* FROM "users" WHERE (CONCAT("users"."first_name", "users"."last_name")) ILIKE '%admin%'

There are other methods given in the documentation that you can use

You might want a space in your concat

concat = Arel::Nodes::NamedFunction.new(
 'concat',
  [arel_table[:first_name], 
  ' ', 
  arel_table[:last_name]]
)
like image 37
usha Avatar answered Oct 27 '22 15:10

usha