19
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

railsでmysqlのJSON型を扱う

Last updated at Posted at 2017-10-11

ActiveRecordでJSON型のカラムを読み書きする時用のメモ

環境

  • MySQL 5.7
  • rails 5.1.3

コード

scheme.rb
create_table "foo_models", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
  t.json "hoge"
end
  • create
FooModel.create(
  hoge: {
    name: 'yamada',
    age:  22,
    sex:  0
  }
)
  • get
foo = FooModel.first
foo.hoge['name']
=> "yamada"

※取得の際にシンボル指定(foo.hoge[:name])だとダメなようです

ransackの検索に対応する

公式Wikiのここの対応でいけるかと思ったけどうまく動かなかったので追記でメモしておきます。
JSON型といっても中身は文字列なのでLIKE検索で力強く取得します。

foo_model.rb
  ransacker :hoge_name, formatter: -> v { "\"name\": \"#{v}\"" } { Arel.sql('hoge') }

これで

FooModel.ransack(hoge_name_cont: 'yamada').result

このように検索できるようになります。

19
25
1

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
19
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?