stu*_*ney 4 ruby sql activerecord ruby-on-rails
我有一个带有cached_info字段的City模型,它是一个序列化的哈希.
{:population=>20000, :more_stuff =>....}
Run Code Online (Sandbox Code Playgroud)
如果我在Activerecord中进行以下查询.
City.where('cached_info[:population] > 300').count
Run Code Online (Sandbox Code Playgroud)
我回来了......
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)
Run Code Online (Sandbox Code Playgroud)
任何人有一个解决方法吗?
除非你LIKE在查询中使用a (但是这不能像>和那样进行比较<),否则通过ActiveRecord和SQL在序列化哈希中查询是没有简单的方法.
根据您的用例,您应该重新考虑您的数据模型,并将这些字段规范化为适当的模型/列.