【问题标题】:Activerecord Where with a hash value带有哈希值的 Activerecord Where
【发布时间】:2011-05-29 15:02:37
【问题描述】:

我有一个带有 cached_info 字段的 City 模型,它是一个序列化的哈希。

{:population=>20000, :more_stuff =>....}

如果我在 Activerecord 中进行以下查询。

City.where('cached_info[:population] > 300').count

我回来了……

ActiveRecord::StatementInvalid: Mysql2::Error: 
You have an error in your SQL syntax; 
check the manual that corresponds to your MySQL server version for the right syntax to use near '[:population] > 300)' at line 1: SELECT COUNT(*) FROM `places` WHERE `places`.`type` = 'City' AND (cached_info[:population] > 3)

有人有解决方法吗?

【问题讨论】:

  • 以后不要在数据库中存储哈希值 ;) 努力学习吧?

标签: sql ruby-on-rails ruby activerecord


【解决方案1】:

没有简单的方法通过 ActiveRecord 和 SQL 在序列化哈希中查询,除非您在查询中使用 LIKE(但这不能像 >< 那样进行比较)。

根据您的用例,您应该真正重新考虑您的数据模型并将这些字段规范化为适当的模型/列。

【讨论】:

    【解决方案2】:

    正如 Jits 所说,LIKE/ILIKE 会起作用,例如:

    City.where('cached_info LIKE ?', '%name: Louisiana%')
    

    【讨论】:

      【解决方案3】:

      如果您使用带有 JSONB 字段的 PostgreSQL 来存储您的哈希值,您可以在where 中下拉到 SQL 并使用如下内容:

      City.where("cast(cached_info ->> 'population' as int) > ?", 300)
      

      ->> 是 Postgres JSONB 访问运算符 -- check out this article

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-24
        • 1970-01-01
        • 2020-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多