【问题标题】:Find articles where array在数组中查找文章
【发布时间】:2015-07-06 21:54:18
【问题描述】:

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

我要根据数组查找文章

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"}')

这会找到它,但我只是希望它在您只键入一个数组时找到它。

谢谢

【问题讨论】:

    标签: ruby-on-rails arrays postgresql


    【解决方案1】:

    找到了答案:

    Article.where('tags @&gt; ?', '{xbox}')

    这将找到每个带有xbox 标签的Article

    编辑:

    这里有一个不同的语法,它做同样的事情:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      • 2014-01-11
      • 2014-07-18
      • 1970-01-01
      • 2012-12-17
      • 1970-01-01
      相关资源
      最近更新 更多