【问题标题】:ROR API Trying to create a zip code searchROR API 尝试创建邮政编码搜索
【发布时间】:2020-04-15 03:01:20
【问题描述】:

到目前为止,我运行了单独的 zip+5 和 zip+9 搜索。我想创建一个搜索,返回与输入一样具体的结果,并在可能的情况下更具体(用户输入 +5,他们得到包含 +5 和 +9 的结果,用户输入 +9 只返回匹配 +9)

这是我目前所拥有的

scope :by_postal9, ->(postal_code) { where('postal_code = ?', (postal_code)) } #9 digit
scope :by_postal5, ->(postal_code) { where('postal_code = ?', (postal_code[0..4])) } #5 digit
scope :by_postal, ->(postal_code) { where('postal_code = ?', (postal_code[0..4])) or where('postal_code = ?', (postal_code)) } #all lengths

使用数据集

ID \ postal_code
1  \ 92110-4441
2  \ 92110
3  \ 92110-4441 

我的 9 位搜索似乎是最好的,它返回 +5 或 +9 搜索的匹配结果没有问题,但只返回完全匹配(使用 92110 搜索 postal9 产生 1 个结果,使用 92110-4441 搜索产生2 个结果,不重叠)

5 位搜索的操作如您所料,输入 9 位 zip 后,会返回 5 位结果的匹配项,但只有 5 位结果(使用 92110-4441 搜索 postal5 会返回 1 个结果,ID 2)

最后一个示例可能只是垃圾,但这是我获得综合结果的最后努力。

【问题讨论】:

    标签: ruby-on-rails ruby postgresql


    【解决方案1】:

    你为什么不用LIKE

    scope :by_postal, ->(postal) { where('postal_code LIKE ?', "#{postal}%") }
    

    如果您的 postal 是 5 位数字,它会返回 5 位数字和 9 位数字的变体。如果是 9 位 -- 仅限 9 位。

    【讨论】:

      【解决方案2】:

      我会使用单独的范围

      by_postal, ->(postal_code) { where('postal_code LIKE ?', "%#{}%") }
      by_length, ->(length) { where('LEN(postal_code) = ?', length) }
      
      • 为 +5 by_postal('211').by_length(5)
      • 为 +9 by_postal('211').by_length(9)
      • by_postal('211')

      【讨论】:

      • 我不确定LEN 函数是否可以跨不同的 sql 服务器移植
      猜你喜欢
      • 1970-01-01
      • 2016-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多