在Rails 4中使用`CONCAT` w/Arel

Kyl*_*cot 9 ruby ruby-on-rails arel ruby-on-rails-4

我有一个User有模式first_namelast_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)


ush*_*sha 7

如果你想要一个平等的搜索

 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)

  • 有没有DB不可知的方法来实现这一目标?现在我必须检查我的数据库适配器(stinks)是什么在两个SQLite中工作:"first_name ||''|| last_name"和Postgres:SQLite:"CONCAT(first_name,'',last_name)" (3认同)