Kyl*_*cot 9 ruby ruby-on-rails arel ruby-on-rails-4
我有一个User有模式first_name和last_name属性.使用Arel我想使用CONCAT.来执行全名搜索.我已经阅读了如何在ARel中使用像CONCAT()等函数的帖子?这给了我指示这是可能的,但我不能完全正确的语法.到目前为止我有
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
Run Code Online (Sandbox Code Playgroud)
sha*_*_ru 13
使用最新的Arel,它需要使用Arel::Nodes.build_quoted(' ')而不仅仅是String('').所以现在的答案是:
SEPARATOR = Arel::Nodes.build_quoted(' ')
Arel::Nodes::NamedFunction.new(
'concat',
[arel_table[:first_name], SEPARATOR, arel_table[:last_name]]
)
Run Code Online (Sandbox Code Playgroud)
如果你想要一个平等的搜索
where(concat.eq("john smith"))
SELECT "users".* FROM "users" WHERE CONCAT("users"."first_name", "users"."last_name") = 'john smith'
Run Code Online (Sandbox Code Playgroud)
如果你想要一个像搜索
where(concat.matches("%john smith%"))
SELECT "users".* FROM "users" WHERE (CONCAT("users"."first_name", "users"."last_name")) ILIKE '%admin%'
Run Code Online (Sandbox Code Playgroud)
您可以使用文档中提供的其他方法
您可能需要在concat中有空格
concat = Arel::Nodes::NamedFunction.new(
'concat',
[arel_table[:first_name],
' ',
arel_table[:last_name]]
)
Run Code Online (Sandbox Code Playgroud)