【问题标题】:ActiveRecord find records that start with one of the words in an arrayActiveRecord 查找以数组中某个单词开头的记录
【发布时间】:2014-03-28 17:18:09
【问题描述】:

我知道下面的查询会找到字段值以某个前缀开头的记录。

MyModel.where("field LIKE ?", "#{prefix}%")

查找字段值以数组中的某个单词开头的记录的查询是什么?

编辑:我在这里找到了其他语言的解决方案:SQL LIKE % inside array 顺便说一句,我正在使用 MySQL DB。

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    应该这样做:

    prefixes = ['mega', 'hyper', 'super']
    sql_conditions = prefixes.map{ |prefix| "field ILIKE #{sanitize("#{prefix}%")}" }.join(' OR ')
    MyModel.where(sql_conditions)
    

    在我的 IRB 控制台中:

    prefixes = ['mega', 'hyper', 'super']
    sql_conditions = prefixes.map{ |prefix| "field ILIKE #{ActiveRecord::Base.sanitize("#{prefix}%")}" }.join(' OR ')
    # => "field ILIKE 'mega%' OR field ILIKE 'hyper%' OR field ILIKE 'super%'"
    

    替代方案,仅适用于 MySQL:

    prefixes = ['^mega', '^hyper', '^super'] # the ^ wildcard represents the start of line
    sql_conditions = "field RLIKE '#{prefixes.join('|')}'" # RLIKE is also known as REGEXP
    MyModel.where(sql_conditions)
    

    【讨论】:

    • 谢谢!所有出色的解决方案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2021-02-15
    相关资源
    最近更新 更多