How can I query Rails ActiveRecord data stored in arrays How can I query Rails ActiveRecord data stored in arrays ruby ruby

How can I query Rails ActiveRecord data stored in arrays


Here are the examples given in the current Rails Edge Guides:

# db/migrate/20140207133952_create_books.rbcreate_table :books do |t|  t.string 'title'  t.string 'tags', array: true  t.integer 'ratings', array: trueendadd_index :books, :tags, using: 'gin'add_index :books, :ratings, using: 'gin'# app/models/book.rbclass Book < ActiveRecord::Baseend# UsageBook.create title: "Brave New World",            tags: ["fantasy", "fiction"],            ratings: [4, 5]## Books for a single tagBook.where("'fantasy' = ANY (tags)")## Books for multiple tagsBook.where("tags @> ARRAY[?]::varchar[]", ["fantasy", "fiction"])## Books with 3 or more ratingsBook.where("array_length(ratings, 1) >= 3")


Have you tried MentorData.where("'apple' = ANY (os_usage)")?


Maybe you should detach the os_usage array from your model and make it a separate table.

In ActiveRecord world you will get something like the following code:

class MentorData < ActiveRecord::Base  ..  has_and_belongs_to_many :os_usage  ..endclass OsUsage < ActiveRecord::Base  ..  has_and_belongs_to_many :mentors_data  ..end

Creating a many_to_many relationship between this two models, allows you to query easily and avoid duplications. This technique is called normalization.

Using this new design you have your collection of os_usage made by objects instead of strings

MentorData.first.os_usage# => [#<OsUsage:....>, #<OsUsage:...>]

Which you can convert easy into the old array of strings

MentorData.first.os_usage.map(&:name)# => ['apple',  'linux']

In addition, you can query the data for all MentorData that includes the os_usage of apple:

MentorData.joins(:os_usages).where('os_usages.name' => 'apple')

And also query all the MentorData records for an OsUsage:

OsUsage.where(name: 'apple').mentors_data

I hope you find it useful :)