我有一个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')
解决方法
以下是当前
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")