问题描述
假设我有以字符串数据类型存储宠物数组的用户数据
[#<用户 id: 1, name: "John", pets: "---\n- cat\n- dog\n- bunny\n- ''\n">,#<用户ID:2,姓名:Pete",宠物:---\n- dog\n- bunny\n- ''\n">,#<用户 id: 3, name: "Jack", pets: "---\n- cat\n- ''\n">,#<用户 id: 4, name: "Kurt", pets: "---\n- cat\n- bunny\n- ''\n">]我可以获取所有拥有猫的用户吗?也许像 User.find_all_by...
或 User.where(....)
或任何作为关系返回的东西?所以我可以通过活动记录查询进行订购.
我知道我可以得到所有有猫的用户
User.all.select{|s|YAML.load(s.pets).include?'cat'}
,但它转换为无法通过活动记录查询排序的数组.
感谢您的帮助.
您可以使用简单的 SQL 来查看cat"是否出现在序列化列中.
User.where('pets LIKE "%cat%"').all
Suppose I have Users data that store array of pet in String datatype
[
#<User id: 1, name: "John", pets: "---\n- cat\n- dog\n- bunny\n- ''\n">,
#<User id: 2, name: "Pete", pets: "---\n- dog\n- bunny\n- ''\n">,
#<User id: 3, name: "Jack", pets: "---\n- cat\n- ''\n">,
#<User id: 4, name: "Kurt", pets: "---\n- cat\n- bunny\n- ''\n">
]
Can i get all users that has a cat? Maybe something like User.find_all_by...
or User.where(....)
or anything that return as a relation? So i can order with active record query.
I know i can get all users that has a cat with
User.all.select{|s| YAML.load(s.pets).include?'cat'}
, but it convert to array that cannot be ordered with active record query.
thx for helping.
You could use simple SQL to see if 'cat' shows up in the serialized column.
User.where('pets LIKE "%cat%"').all
这篇关于Rails 活动记录查询,序列化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!