[英]Selecting rows where array elements in Array Rails ActiveRecord/SQL
In Rails 4/Ruby 2.1, I'm trying to do something like this: 在Rails 4 / Ruby 2.1中,我正在尝试执行以下操作:
@user.submissions.where(:submission_codes_array => valid_submission_codes_array).count
Sort of similar to when you want to see if the :id
if within an array of possible values (ie .where(:id => valid_ids)
, except in this case checking if a particular attribute (which is a postgres array type) includes ANY values that are within the set of possible values, in which case it is then counted. 类似于您要查看
:id
是否在可能值数组(即.where(:id => valid_ids)
,如果在这种情况下,检查特定属性(它是postgres数组类型)是否包含可能值集中的任何值,在这种情况下,将对其进行计数。
Any ideas? 有任何想法吗?
AFAIK, you can't do it through ActiveRecord because you're using Postgres-only features (aka, I don't think mysql supports the functions you need). AFAIK,您无法通过ActiveRecord进行操作,因为您使用的是仅限Postgres的功能(又名,我认为mysql不支持所需的功能)。
What you want can be found here: http://www.postgresql.org/docs/8.2/static/functions-array.html 您想要的内容可以在这里找到: http : //www.postgresql.org/docs/8.2/static/functions-array.html
Specifically, you'll end up with something like Model.where("submission_codes_array && ?", valid_submission_codes_array.to_s.gsub('"',"'"))
. The &&
operator will check for overlap (aka, set intersection) between the two arrays, if I'm reading the docs right. 具体来说,您最终会得到类似
Model.where("submission_codes_array && ?", valid_submission_codes_array.to_s.gsub('"',"'"))
类的Model.where("submission_codes_array && ?", valid_submission_codes_array.to_s.gsub('"',"'"))
。 &&
运算符将检查两者之间是否存在重叠(也就是设置交集)这两个数组,如果我没看错文档的话。
Note that, alas, ActiveRecord doesn't serialize the array into the form Postgres likes, so you gotta tweak it a bit. 注意,Active,ActiveRecord不会将数组序列化为Postgres喜欢的形式,因此您需要对其进行一些调整。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.