Skip to content

Instantly share code, notes, and snippets.

@brainwire
Created October 30, 2014 11:47
Show Gist options
  • Save brainwire/a6fd3f84404be36e6d26 to your computer and use it in GitHub Desktop.
Save brainwire/a6fd3f84404be36e6d26 to your computer and use it in GitHub Desktop.
using Arrays in Rails with PostgreSQL
class AddSubjectsToBook < ActiveRecord::Migration
def change
add_column :books, :subjects, :text, array:true, default: []
end
end
2.1.2 :026 > Book.where("'history' = ANY (subjects)")
Book Load (0.5ms) SELECT "books".* FROM "books" WHERE ('history' = ANY (subjects))
=> #<ActiveRecord::Relation [#<Book id: "39abef75-56af-4ad5-8065-6b4d58729ee0", title: nil, created_at: "2014-10-17 08:21:17", updated_at: "2014-10-17 19:21:25", description: {}, metadata: {}, subjects: ["education", "business", "history", "finances"]>]>
2.1.2 :027 > Book.where("subjects @> ?", '{finances}')
Book Load (0.5ms) SELECT "books".* FROM "books" WHERE (subjects @> '{finances}')
=> #<ActiveRecord::Relation [#<Book id: "39abef75-56af-4ad5-8065-6b4d58729ee0", title: nil, created_at: "2014-10-17 08:21:17", updated_at: "2014-10-17 19:21:25", description: {}, metadata: {}, subjects: ["education", "business", "history", "finances"]>]>
rails g migration add_subjects_to_book subjects:text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment