【问题标题】:Querying a hash column in Rails在 Rails 中查询哈希列
【发布时间】:2015-06-03 05:20:53
【问题描述】:

我的表 table_1 中有一个哈希列 hash_column。

在table_1.rb中

serialize :hash_column, Hash

列中存储的值是

            hash_column
record1 => { index1 => '2'} 
record2 => { index2 => '3' } 
record3 => { index1 => '4'}

我想获取 hash_column 的键为 index1 的所有记录。 我现在的做法是

 table_1.where("hash_column LIKE ?", "%index1%" )

这很好用。但是在 Rails 中,有没有一种正确的方法来使用哈希列的键和值来查询它?

ps:我用的是mysql数据库

【问题讨论】:

  • 嘿!检查此article。希望对您有所帮助!
  • 如果你使用 Postgres,有 Hstore 非常适合存储 Hash 数据,我们可以像使用 activerecord 一样轻松查询它们。schneems.com/post/19298469372/…
  • 我想用mysql数据库来实现。

标签: mysql ruby-on-rails ruby hash rails-activerecord


【解决方案1】:

不能用 SQL 来完成。您无法查询您的Hash,因为它在text 列中被序列化为yaml(或json)。所以基本上您的数据库不知道该列的结构,因为它只是文本。

您可以尝试为您的列使用其中一种 JSON 类型

https://dev.mysql.com/doc/refman/5.7/en/json.html

并使用JSON_EXTRACT 或其他功能并在您的where clause 中使用它

更多信息 https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html

【讨论】:

    猜你喜欢
    • 2016-04-22
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多