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
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]]
)
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]]
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With