[英]Querying a hash column in Rails
我的表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數據庫
使用SQL無法完成。 您無法查詢Hash
因為它在text
列中被序列化為yaml
(或json
)。因此,基本上,您的數據庫不知道列的結構,因為它只是文本。
您可以嘗試為列使用JSON類型之一
https://dev.mysql.com/doc/refman/5.7/zh-CN/json.html
並使用JSON_EXTRACT
或其他函數並在where clause
更多信息https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.