Build Status Coverage Status

JSON on Rails

This gem adds native support for MySQL [5.7] JSON data type to Rails 4.

Introduction

Rails 5 introduced native support for the [MySQL] JSON data type; however, due to the Rails feature policy, version 4 won't be receive this functionality.

This gem adds a Rails JSON data type, allowing the user to work with JSON attributes transparently, as a Array/Hash/etc.

The inner working is simple, and uses the standard Rails (internal) APIs; this is explained in a blog post of mine.

Installation

Add the gem to the Gemfile of your rails project:

gem "json_on_rails", "~> 0.1.0"

and update the Gemfile.lock:

$ bundle install

that's all!

Usage/example

Create a table:

class CreateUsers < ActiveRecord::Migration
  def up
    create_table "migration_models" do |t|
      t.string "login", null: false, limit: 24
      t.column "extras", :json
    end
  end
end

or add the column to an existing one:

class CreateUsers < ActiveRecord::Migration
  def up
    add_column "users", "extras", :json
  end
end

define the model:

class User < ActiveRecord::Base
  attribute :extras, ActiveRecord::Type::Json.new
end

then (ab)use the new attribute!:

user = User.create!(login: "saverio", extras: {"uses" => ["mysql", "json"]})
user.extras.fetch("uses") # => ["mysql", "json"]

Don't forget that JSON doesn't support symbols, therefore, they can be saved, but are accessed/loaded as strings.

Users are encouraged to have a look at the test suite (here and here) for an exhaustive view of the functionality.

Limitations

The column creation t.json <column_name> syntax is currently unsupported.