如何查询存储在数组中的Rails ActiveRecord数据 [英] How can I query Rails ActiveRecord data stored in arrays

查看:72
本文介绍了如何查询存储在数组中的Rails ActiveRecord数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为MentorData的Rails模型,它有一个名为 os_usage 的属性。 oses存储在像这样的数组中,例如 ['apple','linux']

I have a rails model call MentorData and it has an attribute called os_usage. The oses are stored in an array like so ['apple', 'linux'].

回顾一下:

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

我希望能够查询所有数据MentorData包含 apple 的os_usage,但是当我搜索 MentorData.where(os_usage:'apple')时,获得只能使用Apple而不能使用Apple和Linux的指导者。我需要以某种方式进行搜索,以检查数组中是否包含苹果。

I am looking to be able to query the data for all MentorData that includes the os_usage of apple, but when I search MentorData.where(os_usage: 'apple') I only get the mentors who can only use apple and not apple and linux. I need to search in some way that checks if apple is included in the array.

我也尝试了以下方法。

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

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

Is it possible to query data in ActiveRecord by attributes that have an array or items?

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

The database is on Postgres if that helps in providing a more raw search query.

推荐答案

以下是当前 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")

这篇关于如何查询存储在数组中的Rails ActiveRecord数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆