代码之家  ›  专栏  ›  技术社区  ›  MLZ

Rails作用域中的正则表达式未捕获正确的值

  •  -1
  • MLZ  · 技术社区  · 7 年前

    " ,1,8,9,10"

    " 0 ,1"
    "4,5"

    我继承的代码捕获了值“0”和“10”,这是错误的:

    scope :short_result_contains_value, -> (game_id, value) { where(game_id: game_id).where('short_result LIKE ?', "%#{value}%")
    

    scope :short_result_contains_value, -> (game_id, value) { where(game_id: game_id).where('short_result ~ ?', "/\b(#{value})\b/")}
    

    运行时,我在日志中看到正在运行以下查询:

    SELECT "game_results".* FROM "game_results" WHERE "game_results"."game_id" = $1 AND "game_results"."game_id" = $2 AND (short_result ~ (0')
    

    我使用的是Postgres,使用的是rails4.2和Ruby 2.3.7。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Wiktor Stribiżew    7 年前

    你可以用

    where('short_result LIKE ?', "#{value},%")
    

    value 后跟逗号。

    这个 LIKE 价值 0 ,所以记录应该从 . 然后,后面应该跟一个逗号。然后 % 通配符匹配记录末尾的任何0+字符。

    .where('short_result ~ ?', "\\y#{value}\\y")
    

    这个 \y 在PostgreSQL中,regex语法是单词边界,与 \b 类似于Perl的regexp。

    .where('short_result ~ ?', "(^|,)#{value}($|,)")
    

    这个 (^|,) 匹配字符串的开头( ^ | )逗号,和 ($|,) $ )或者逗号。