3

I have a Rails model called Box. Each Box object has a column :products, which is an array of strings that includes all the products that are being stored inside it at the time.

For each Box object, it is possible that the same value was stored in another Box.

Is there a query I can use to return all the Boxes that have value x stored in :products?

I know "where" works for finding objects with certain values, and with an array you might use "include?", but I'm having trouble working out a way to use either in this case, if it's at all possible.

2 Answers 2

6

There was an answer posted here before that worked well enough, but I looked around and found another query that was more succinct.

selected_boxes = Box.where("?=ANY(products)", x)

Where x is the value you are seeking in each object.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm using Rails 4.2.5 and i cannot use this query. It said "wrong number of arguments (given 2, expected 1)"
Been trying to figure this out for an hour. Thank you. Not sure why this doesn't have more votes.
0

Scope!

scope :contains, ->(items) { where("products LIKE ?", "%#{items.to_yaml}%") } # items is an array of your potential strings

So you'd call this as Box.contains(%w(foo bar)) or Box.contains(['some thing'])

Passing the array should let you search for multiple items at a time...

You can name the scope anything you want, obviously

LIKE for mySQL... ILIKE for postgreSQL

Comments

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.