简体   繁体   中英

How to query from serialize Hash column in Rails

For example:

class User < ActiveRecord::Base
 serialize :preferences, Hash
end

preferences contains hash record... ex:

{'category' => 'a', 'type' => 'b', 'published' => true}

How can I do some query, where I have to return records that matched/equal to specific key-value in serialized column.

I want to have something like:

.where('preferences.published' => true)

Thanks in advance.

默认情况下,Rails将哈希序列化为YAML,因此您可以执行以下操作:

.where('preferences LIKE "%published: true%"')

You can't use native DB routines to query a serialized field. The only way to do this query is to do

User.all.select { |u| u.preferences['published'] == true }

You only want to serialize fields when you don't want to query on it, and just expose the data 'as it' If you need to global query on it, you should have a table UserPreference for example, with a user_id and the different preferences.

You can 'hack' it doing what @mudasobwa said .where('preferences LIKE "%published: true%"') , but it can be risky.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM