【问题标题】:Search for substring in two columns在两列中搜索子字符串
【发布时间】:2015-09-22 01:33:53
【问题描述】:

我目前有一个范围:

scope :named,->(query) do
  where("(first_name || last_name) ~* ?", Regexp.escape(query || "a default string to prevent Regexp.escape(nil) errors"))
end

这有效,除非 first_name 或 last_name 为 nil。如果其中一列为零,我如何找到这些列?

【问题讨论】:

    标签: ruby-on-rails regex string substring


    【解决方案1】:

    我想你可以试试这样的:

    scope :named,->(query) do
      where("first_name IS NOT NULL OR last_name IS NOT NULL AND (first_name || last_name) ~* ?", Regexp.escape(query || "a default string to prevent Regexp.escape(nil) errors"))
    end
    

    【讨论】:

      【解决方案2】:

      这是搜索姓名的基本范围,它处理“仅名字”、“仅姓氏”或全名搜索。

      如果将查询拆分为数组,则可以抓取数组的第一个和最后一个,无论查询的长度是一个还是两个。

      如果需要,您可以用您的正则表达式替换拆分

      您显然可以对此进行扩展(例如,不区分大小写、排序),但给出了基本概念。

      如果条带失败,还通过默认为空字符串来处理 nil 查询。

      scope :named,->(query) do
        query.strip! rescue query = ""
        query_words = query.split(' ')
        where(["first_name LIKE ? OR last_name LIKE ?", "#{query_words.first}%", "#{query_words.last}%"])
      end
      

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-06
        • 2022-11-19
        • 1970-01-01
        • 2014-06-03
        • 1970-01-01
        相关资源
        最近更新 更多