我有一个rails模型名为MentorData,它有一个名为os_usage的属性.操作系统存储在类似so ['apple', 'linux']的数组中.

总结一下:

$ MentorData.first.os_usage
=> ['apple',  'linux']

我希望能够查询所有导师数据,包括os_使用apple的数据,但当我搜索MentorData.where(os_usage: 'apple')时,我只得到只能使用apple而不能使用apple和linux的导师.我需要以某种方式搜索,以判断数组中是否包含苹果.

我也try 了以下方法.

MentorData.where('os_usage like ?', 'apple’)
MentorData.where('os_usage contains ?', 'apple’)
MentorData.where('os_usage contains @>ARRAY[?]', 'apple')

是否可以通过具有数组或项的属性查询ActiveRecord中的数据?

如果这有助于提供更原始的搜索查询,则数据库位于Postgres上.

推荐答案

以下是当前Rails Edge Guides条中给出的示例:

# db/migrate/20140207133952_create_books.rb
create_table :books do |t|
  t.string 'title'
  t.string 'tags', array: true
  t.integer 'ratings', array: true
end
add_index :books, :tags, using: 'gin'
add_index :books, :ratings, using: 'gin'

# app/models/book.rb
class Book < ActiveRecord::Base
end

# Usage
Book.create title: "Brave New World",
            tags: ["fantasy", "fiction"],
            ratings: [4, 5]

## Books for a single tag
Book.where("'fantasy' = ANY (tags)")

## Books for multiple tags
Book.where("tags @> ARRAY[?]::varchar[]", ["fantasy", "fiction"])

## Books with 3 or more ratings
Book.where("array_length(ratings, 1) >= 3")

Postgresql相关问答推荐

如何在Windows中安装sql for golang

PostgreSQL散列连接与嵌套循环和散列索引

为什么32632投影中的几何图形并不完美?

错误:用户需要系统密码:postgres

如何重新格式化已获取的 psql 查询输出?

如何在 postgres 中查询键设置为空值的 jsonb 字段

如何获取在 Go 中完成的 SQL 插入的错误详细信息?

如何在plpgsql中找到一行中的最大值?

PostgreSQL - 列出模式中的所有唯一约束

postgreSQL 中对 utf-8 的 LC_COLLATE 和 LC_CTYPE 支持

如何让 Flask SQLAlchemy 重用数据库连接?

PG::TRDeadlockDetected:ERROR: deadlock detected

如何使用 node-postgres 将多行正确插入 PG?

如何禁用 postgresql缓存优化?

如何增加 max_locks_per_transaction

在 Postgres 中显示关系、序列和函数的默认访问权限

在 Windows 7 上更改/重置 postgresql 用户密码

在子类的 Hibernate 中 for each 表指定不同的序列

PostgreSQL 无法启动:server.key具有组或世界访问权限

postgresql DB中唯一键的正确数据类型是什么?