Activerecord其中具有散列值

问题描述

| 我有一个带有cached_info字段的城市模型,该字段是序列化的哈希。
{: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)
有人对此有解决方法吗?     

解决方法

        没有一种简单的方法可以通过ActiveRecord和SQL在序列化的Hash中进行查询,除非在查询中使用“ 3”(但这无法进行“ 4”和“ 5”之类的比较)。 根据您的用例,您应该真正地重新考虑您的数据模型,并将这些字段标准化为适当的模型/列。     ,        正如Jits所说,LIKE / ILIKE可以工作,例如:
City.where(\'cached_info LIKE ?\',\'%name: Louisiana%\')
    ,        如果您使用带有JSONB字段的PostgreSQL来存储哈希,则可以在
where
中使用SQL并使用类似以下内容的代码:
City.where(\"cast(cached_info ->> \'population\' as int) > ?\",300)
ѭ9是Postgres JSONB访问运算符-请查看本文。