Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Rails objects that include value in array attribute

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.

like image 942
jmarcs Avatar asked Apr 20 '26 00:04

jmarcs


1 Answers

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.

like image 191
jmarcs Avatar answered Apr 21 '26 14:04

jmarcs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!