0

Using Rails 3.2, I'm working on an API backed model (not ActiveRecord). I want to be able to call to_json on this model in Rails controllers. After reading through a bunch of the ActiveModel docs I'm still not clear on one thing:

Given a model like this:

class MyModel
  attr_accessor :id, :name
  def initialize(data)
    @id = data[:id]
    @name = data[:name]
  end

  def as_json
    {id: @id, name: @name}
  end
end

Should this work as expected, or do I also need to include ActiveModel::Serializers::JSON? I'm having a hard time figuring out where the as_json / to_json methods are normally defined and when Rails calls which ones automatically in different circumstances...

Thanks for any insight!

Andrew
  • 42,517
  • 51
  • 181
  • 281

1 Answers1

5

Yes this does work, however not quote as you've written in.

When you render json in a controller using

def action
  render :json => @my_model
end

Then Rails will automatically call to_json on your object and as long as you've defined to_json this will work as expected.

If your controller uses the Rails 3 content negotiation shenanigans, ie.

class Controller < ApplicationController
  respond_to :json, :html

  def action
    respond_with(@my_model)
  end

Then you will need to override as_json on your class, but the method signature requires an optional hash of options to be compatible with ActiveSupport so in this case you want

def as_json(options={})
  ...
end

Alternatively If you include ActiveModel::Serializers::JSON into your Class and your class supports the attributes method that returns a hash of attrs and their values - then you'll get as_json for free - but without the control of the resultant structure that you have if you just override the method by hand.

Hope this helps.

eightbitraptor
  • 267
  • 2
  • 6
  • Thanks for the "Alternatively If you include ActiveModel::Serializers::JSON into your Class and your class supports the attributes method that returns a hash of attrs and their values" that was key for me implementing a PORO with using AR Serializers. – rainkinz May 14 '14 at 20:46