Rails where clause when something is stored as array

家住魔仙堡 提交于 2019-12-07 08:10:35

问题


I am running rails 4.2, with a PG database.

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

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

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

Obviously this is not working - but how are you meant to do this in rails?


回答1:


According to documentation, something like this should work:

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



回答2:


In addition to @potashin answer, there is a shorter way to do (see documentation) if you need to get Items 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'])


来源:https://stackoverflow.com/questions/35893755/rails-where-clause-when-something-is-stored-as-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!