如何在 Rails 4 中查询数组列?

Chr*_*ung 8 ruby arrays postgresql ruby-on-rails

我找不到任何关于如何array columns在 Rails 中查询的好文章。我遇到了在 Rails 中查询数组列的需要。

我从一篇教如何在这里进行基本查询的文章中找到。

让我们按照文章中的示例进行操作,其中Book涵盖了很多subjects并且主题存储为数组列:

add_column :books, :subjects, :text, array: true, default: []
Run Code Online (Sandbox Code Playgroud)

查询包含特定主题的书籍- 例如历史

Book.where("'history' = ANY (subjects)")
Run Code Online (Sandbox Code Playgroud)

查询包含所有列出主题的书籍- 例如 Finance AND Business AND Accounting

Book.where("subjects @> ?", "{Finance,Business,Accounting}")
Run Code Online (Sandbox Code Playgroud)

我想知道我如何才能做到以下几点?

查询包含任何所列主题的书籍- 例如小说或传记

查询不包含特定主题的书籍- 例如 NOT Physics

查询不包含任何科目的书籍- 例如 NOT (Physics OR Chemistry OR Biology)

有没有Rails办法进行上述查询?

小智 19

为了,

查询包含任何所列主题的书籍 - 例如小说或传记

Book.where("subjects &&  ?", "{Fiction,Biography}")
Run Code Online (Sandbox Code Playgroud)

查询不包含特定主题的书籍 - 例如 NOT Physics

Book.where("subjects <>  ?", "{Physics}")
Run Code Online (Sandbox Code Playgroud)

查询不包含任何科目的书籍 - 例如 NOT (Physics OR Chemistry OR Biology)

Book.where.not("subjects &&  ?", "{Physics,Chemistry,Biology}")
Run Code Online (Sandbox Code Playgroud)

可以参考Postgres的数组函数。

https://www.postgresql.org/docs/8.2/functions-array.html


And*_*eko 6

  1. 通常,关联是解决问题的首选方法:

    Book has_many :subjects # or has_one/has_and_belongs_to_many

    Subject belongs_to :book # or has_and_belongs_to_many

    然后只需创建一个表subjects,将所有主题保存在那里,然后就设置好了。

  2. 您的疑问:

查询包含任何所列主题的书籍 - 例如小说或传记

Book.find_by_sql "SELECT * FROM books WHERE 'Fiction' = ANY (subjects) OR 'Biography' = ANY (subjects)"
Run Code Online (Sandbox Code Playgroud)

查询不包含特定主题的书籍 - 例如 NOT Physics

Book.where.not("subjects @> ?", "{Physics}")
Run Code Online (Sandbox Code Playgroud)

查询不包含任何科目的书籍 - 例如 NOT (Physics OR Chemistry OR Biology)

Book.find_by_sql "SELECT * FROM books WHERE books NOT IN (SELECT * FROM books WHERE 'Physics' = ANY (subjects) OR 'Chemistry' = ANY (subjects) OR 'Biology' = ANY (subjects)"
Run Code Online (Sandbox Code Playgroud)