我有一个带有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)
有人能解决这个问题吗?
除非在查询中使用LIKE
,否则没有简单的方法可以通过ActiveRecord和SQL在序列化哈希中进行查询(但这无法进行>
和<
之类的比较)。
根据您的用例,您应该重新思考您的数据模型,并将这些字段规范化为适当的模型/列。
正如Jits所说,LIKE/ILIKE会起作用,例如:
City.where('cached_info LIKE ?', '%name: Louisiana%')
如果你使用带有JSONB字段的PostgreSQL来存储哈希,你可以在where
中下拉到SQL并使用类似的东西:
City.where("cast(cached_info ->> 'population' as int) > ?", 300)
->>
是Postgres JSONB访问操作符——请参阅本文。