Search code examples
ruby-on-railsjsonrespond-with

Including "type" attribute in json respond_with Rails 3.1


It seems that when returning an object containing a "type" attribute as JSON from a Rails 3.1 application, the "type" attribute is not included. Assume I have the following:

A model with corresponding STI table Animal. Models Cat, Dog and Fish that inherit Animal.

When returning an Animal via JSON, I wish to include the "type" column, but this is not happening:

jQuery.ajax("http://localhost:3001/animals/1", {dataType: "json"});

yields:

responseText: "{"can_swim":false,"created_at":"2012-01-20T17:55:16Z","id":1,"name":"Fluffy","updated_at":"2012-01-20T17:55:16Z","weight":9.0}"

It seems like this is a problem with to_json:

bash-3.2$ rails runner 'p Animal.first.to_yaml'
"--- !ruby/object:Cat\nattributes:\n  id: 1\n  type: Cat\n  weight: 9.0\n  name: Fluffy\n  can_swim: false\n  created_at: 2012-01-20 17:55:16.090646000 Z\n  updated_at: 2012-01-20 17:55:16.090646000 Z\n"

bash-3.2$ rails runner 'p Animal.first.to_json'
"{\"can_swim\":false,\"created_at\":\"2012-01-20T17:55:16Z\",\"id\":1,\"name\":\"Fluffy\",\"updated_at\":\"2012-01-20T17:55:16Z\",\"weight\":9.0}"

Does anyone know the reasoning behind this behavior, and how to override it?


Solution

  • Override the as_json method. It's used by to_json in order to produce the output. You can do something like:

    def as_json options={}
     {
       id: id,
       can_swim: can_swim,
       type: type
     }
    end