0

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 (i.e. .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?

0

1 Answer 1

0

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.

1
  • Awesome, just got it to be functional. Originally was having some issues, as I was doing this: Model.where("submission_codes_array && ?", [1,5,2].to_s). But it appears as though the second array you pass in needs to have the proper Postgres array format. So something like this worked: Model.where("submission_codes_array && ?", '{1,5,2}'"). Commented Jul 24, 2014 at 6:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.