Back to Jots

Serialize an attribute as JSON in Rails 3

The serialize method in Rails is a useful method that serializes a complex attribute (like a Hash) before storing it in the database. Here’s an example of one such scenario where the serialize method is useful.

# In models/user.rb
class User < ActiveRecord::Base
 serialize :preferences # ActiveRecord will serialize the preferences hash as YAML by default
end

Rails 3 serializes an attribute to YAML by default. However, JSON is a more suitable choice these days (Postgres, for example, can now query data in JSON). If you wish to serialize an attribute as JSON in Rails, here’s how you can do it. Create a file lib/active_record_json_coder.rb and copy paste the code below

# In lib/active_record_json_coder.rb

# This is a custom coder that serializes an attribute as JSON
class ActiveRecordJSONCoder
  class << self
    def dump(hash)
      ActiveSupport::JSON.encode(hash)
    end

    def load(json)
      return if json.nil?
      ActiveSupport::JSON.decode(json)
    end
  end
end

Modify your model to use the ActiveRecordJSONCoder class to serialize and deserialize attributes

# In models/user.rb
class User < ActiveRecord::Base
  serialize :preferences, ActiveRecordJSONCoder
end

ActiveRecord will now serialize the attribute as JSON

[22] pry(main)> user = User.create!(preferences: { "use_new_interface" => true })
[22] pry(main)> puts ActiveRecord::Base.connection.execute("SELECT * FROM users WHERE users.id = #{user.id}").first["preferences"]
{"use_new_interface":true}

Built with Hugo & Notion. Source code is available at GitHub.