【问题标题】:String concatenation of two attributes in Rails where queryRails where查询中两个属性的字符串连接
【发布时间】:2015-06-22 22:49:50
【问题描述】:

假设我有一个用户的 attrs first_namelast_name。我知道用户的全名是“Johnny Appleseed”,因为我有大量用户全名作为字符串的哈希。

当然,我可以先拆分每个字符串,然后像这样搜索: User.where(first_name: 'Johnny', last_name: "Appleseed")

但是,我想知道是否有一种方法可以在查询中将两者基本上连接起来,基本上像这样: User.where('first_name + last_name = ?', 'Johnny Appleseed')

或者如果我可以在 User 模型上有一个 full_name 方法,并通过它进行搜索?

 def full_name
    "#{self.first_name} #{self.last_name}"
  end

User.where('full_name = ?', 'Johnny Appleseed')

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord


    【解决方案1】:

    可能最简单的解决方案是:

    User.where(%q(concat_ws(' ', first_name, last_name) = ?), 'Johnny Appleseed')
    

    【讨论】:

    • 这行得通,谢谢!在性能方面,它很慢,但它可以完成工作。我不知道concat_ws,感谢您向我展示了一些新东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    相关资源
    最近更新 更多