【问题标题】:Using `CONCAT` w/ Arel in Rails 4在 Rails 4 中使用带有 Arel 的`CONCAT`
【发布时间】:2013-12-24 06:22:29
【问题描述】:

我有一个具有first_namelast_name 属性的User 模型。使用 Arel 我想使用 CONCAT 执行全名搜索。我已经阅读了How do I use functions like CONCAT(), etc. in ARel? 的帖子,这表明这是可能的,但我不能完全正确地理解语法。到目前为止我有

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

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 arel


    【解决方案1】:

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

     where(concat.eq("john smith"))
    
     SELECT "users".* FROM "users" WHERE CONCAT("users"."first_name", "users"."last_name") = 'john smith'
    

    如果你想要一个类似的搜索

    where(concat.matches("%john smith%"))
    
     SELECT "users".* FROM "users" WHERE (CONCAT("users"."first_name", "users"."last_name")) ILIKE '%admin%'
    

    documentation 中给出了其他方法,您可以使用

    你可能想在你的 concat 中有一个空格

    concat = Arel::Nodes::NamedFunction.new(
     'concat',
      [arel_table[:first_name], 
      ' ', 
      arel_table[:last_name]]
    )
    

    【讨论】:

    • 是否有与数据库无关的方法来实现这一目标?现在我必须检查什么是我的数据库适配器(臭名昭著)才能在 SQLite 中工作:“first_name || ''|| last_name”和 Postgres:SQLite:“CONCAT(first_name,'',last_name)”
    • 2015 年底与 Arel 连接的节点 was added
    【解决方案2】:

    对于最新的 Arel,需要使用 Arel::Nodes.build_quoted(' ') 而不仅仅是字符串 (' ')。所以现在的答案是:

    SEPARATOR = Arel::Nodes.build_quoted(' ')
    
    Arel::Nodes::NamedFunction.new(
      'concat',
      [arel_table[:first_name], SEPARATOR, arel_table[:last_name]]
    )
    

    【讨论】:

    • Arel::Nodes.build_quoted(' ') 在 Arel >= 6 中定义,它对我不起作用(Rails 4.0)。在这种情况下,只需将其替换为 ' '
    猜你喜欢
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多