Rails where where when something is stored as an array

I am running rails 4.2 with a PG database.

I have an item stored in a database such as (model Item ):

 :something => ["1", "2", "3"] 

I would like to get Item.where(:something.include? => "3")

Obviously, this does not work - but how are you going to do it on rails?

+5
source share
2 answers

According to the documentation , something like this should work:

 Item.where('something @> ARRAY[?]::varchar[]', ['3']) 
+6
source

In addition to @potashin's answer, there is a shorter way (see the documentation ) if you need to get elements on one element.

 # Items for a single something Item.where("'3' = ANY (something)") # Or using '?' Item.where('? = ANY (something)', '3') # Items for multiple something Item.where('something @> ARRAY[?]::varchar[]', ['3', '4']) 
+2
source

Source: https://habr.com/ru/post/1244739/


All Articles