Created
October 30, 2014 11:47
-
-
Save brainwire/a6fd3f84404be36e6d26 to your computer and use it in GitHub Desktop.
using Arrays in Rails with PostgreSQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AddSubjectsToBook < ActiveRecord::Migration | |
def change | |
add_column :books, :subjects, :text, array:true, default: [] | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"]>]> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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