準備
Ubuntu server12.04にPostgreSQL9.3をインストールする
hstoreエクステンションを導入できるようsuper userにしておく
1 | create user vagrant superuser password 'password' login; |
Ubuntu Server12.04でPostgreSQL9.3をつかう〜hstore
gem pgをインストールするためにdevまでインストール
1 | sudo apt-get install postgresql-server-dev-9.3 |
rails new
1 | rails new APP_NAME -d postgresql |
config/database.yml
developmentとtestをつくる
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | development: adapter: postgresql encoding: unicode database: pg_app_development pool: 5 username: vagrant password: password test: adapter: postgresql encoding: unicode database: pg_app_test pool: 5 username: vagrant password: password |
1 | rake db:create |
hstoreとarrayを試してみる
migrationファイルの変更
1 | rails g scaffold article name content:text published_on:date tags properties:hstore |
excute “create extension hstore”とarray:true
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class CreateArticles < ActiveRecord::Migration def change create_table :articles do |t| execute "create extension hstore" t.string :name t.text :content t.date :published_on t.string :tags, array: true t.hstore :properties t.timestamps end end end |
挿入
普通にハッシュや配列をいれられる
1 | Article.create(name: 'hello', tags:["ttt1", "ttt2"], properties: {author: "none"}) |
読込
配列の要素で検索はANY
1 | Article.where("? = ANY(tags)", "ttt2") |
ハッシュの値の検索は->
1 | Article.where("properties -> 'author' LIKE '%on%'") |
配列やハッシュのように扱える
1 2 3 4 5 6 7 8 | 2.1.0 :007 > a.properties["key"] = 2 => 2 2.1.0 :008 > a.save (0.2ms) BEGIN (0.2ms) COMMIT => true 2.1.0 :009 > a => #<Article id: 1, name: "hello", content: nil, published_on: nil, tags: ["ttt1", "ttt2"], properties: {"author"=>"none", "key"=>2}, created_at: "2014-01-02 14:48:50", updated_at: "2014-01-02 14:48:50"> |
1 2 3 4 5 6 7 8 | 2.1.0 :010 > a.tags => ["ttt1", "ttt2"] 2.1.0 :011 > a.tags.push 8 => ["ttt1", "ttt2", 8] 2.1.0 :012 > a.save (0.4ms) BEGIN (0.2ms) COMMIT => true |