Search code examples
ruby-on-railsrubyruby-on-rails-4arel

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

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