sql – 如何查询存储在数组中的Rails ActiveRecord数据
发布时间:2021-01-11 08:10:40 所属栏目:编程 来源:网络整理
导读:我有一个rails模子挪用MentorData,它有一个名为os_usage的属性. ose存储在一个像[‘apple’,’ linux‘]这样的数组中. 回首一下: $MentorData.first.os_usage= ['apple','linux'] 我但愿可以或许查询包括苹果os_usage的全部MentorData的数据,可是当我搜刮MentorD
|
我有一个rails模子挪用MentorData,它有一个名为os_usage的属性. ose存储在一个像[‘apple’,’ linux‘]这样的数组中. 回首一下: $MentorData.first.os_usage => ['apple','linux'] 我但愿可以或许查询包括苹果os_usage的全部MentorData的数据,可是当我搜刮MentorData.where(os_usage:’apple’)时,我只会获得只能行使苹果而不是苹果和Linux的导师.我必要以某种方法搜刮,搜查数组中是否包括apple. 我也实行了以下内容. 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") (编辑:湖南网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
站长推荐
热点阅读


