查找数组的文章

时间:2015-07-06 21:54:19

标签: ruby-on-rails arrays postgresql

我目前正在将数据库中的标签存储为数组字符串

我想找到基于数组的文章

Article.find_by(tags: 'xbox')

但这会带来错误。

此外:

Article.where(tags: 'xbox')

这告诉我必须插入{}来查找数组

Article.where(tags: '{xbox}')

这不会带来任何错误,但它也找不到任何错误

#=> #<Article id: 4, name: "Playstation 3", price: 150.0, description: "testing description and tags", created_at: "2015-07-06 21:29:24", updated_at: "2015-07-06 21:29:24", user_id: 1, category_id: 2, puerto_rico_city_id: 1, tags: ["", "playstation 3", "playstation", "xbox", "test"]> 

如果我这样做

Article.where(tags: '{"", "playstation 3", "playstation", "xbox", "test"}')

这会找到它,但我只想在你输入一个数组时找到它。

由于

1 个答案:

答案 0 :(得分:0)

找到答案:

Article.where('tags @> ?', '{xbox}')

这将找到标记为Article的每个xbox

编辑:

这里有不同的语法:

Article.where(['? = ANY (tags)', 'xbox'])