如何查询存储在数组中的Rails ActiveRecord数据

编程入门 行业动态 更新时间:2024-10-27 11:21:47
本文介绍了如何查询存储在数组中的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数据

本文发布于:2023-10-24 15:02:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524256.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   数据   Rails   ActiveRecord

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!