简体   繁体   中英

Selecting rows where array elements in Array Rails ActiveRecord/SQL

In Rails 4/Ruby 2.1, I'm trying to do something like this:

@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.

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).

What you want can be found here: 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.

Note that, alas, ActiveRecord doesn't serialize the array into the form Postgres likes, so you gotta tweak it a bit.

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