LoginSignup
2
2

More than 5 years have passed since last update.

PostgreSQLのjsonb型とActiveRecord

Posted at

postgresql9.4で組み込まれたjsonb型をActiveRecordから扱う実験

準備

とりあえずテーブルを作る。(migrationはつかわない)

=# create table tests (id serial primary key, body jsonb);
=# insert into tests (body) values ('{"attrs":[2,3,5],"is_hoge":true,"text":"aaaa bbb"}');

ARから

json演算子->をつかってjsonbデータ内の一部をとってくるテスト

require "active_record"
require "pp"

ActiveRecord::Base.establish_connection(
  adapter: "postgresql",
  encoding: "unicode",
  host:     "localhost",
  database: "sandbox",
)

class Test < ActiveRecord::Base
end


b =  Test.select("body->'attrs'->2  as foo").first

p b.foo #=> 5
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2