Question

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
Was it helpful?

Solution

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]]
)

OTHER TIPS

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]]
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top