views:

323

answers:

2

I'm trying to override as_json in one of my models, partly to include data from another model, partly to strip out some unnecessary fields. From what I've read this is the preferred approach in Rails 3. To keep it simple, let's say I've got something like:

class Country < ActiveRecord::Base
  def as_json(options={})
    super(
      :only => [:id,:name]
    )
  end
end

and in my controller simply

def show
  respond_to do |format|
    format.json  { render :json => @country }
  end
end

Yet whatever i try, the output always contains the full data, the fields are not filtered by the ":only" clause. Basically, my override doesn't seem to kick in, though if I change it to, say...

class Country < ActiveRecord::Base
  def as_json(options={})
    {foo: "bar"}
  end
end

...I do indeed get the expected JSON output. Have I simply got the syntax wrong?

A: 

Some further testing, in the controller action:

format.json { render :json => @country }

And in the model:

class Country < ActiveRecord::Base
    has_many :languages
    def as_json(options={})
        super(
            :include => [:languages],
            :except => [:created_at, :updated_at]
        )
    end
end

Outputs:

{
    created_at: "2010-05-27T17:54:00Z"
    id: 123
    name: "Uzbekistan"
    updated_at: "2010-05-27T17:54:00Z"
}

However, explicitly adding .to_json() to the render statement in the class, and overriding to_json in the model (instead of as_json) produces the expected result. With this:

format.json { render :json => @country.to_json() } 

in my controller action, and the below in the model, the override works:

class Country < ActiveRecord::Base
    has_many :languages
    def to_json(options={})
        super(
            :include => [:languages],
            :except => [:created_at, :updated_at]
        )
    end
end

Outputs...

{
    id: 123,
    name: "Uzbekistan",
    languages: [
        {id: 1, name: "Swedish"},
        {id: 2, name: "Swahili"}
    ]
}

...which is the expected output. Have I found a bug? Do I win a prize?

Ola Tuvesson
Do you have a plugin or something installed that defines its own `to_json` or `as_json`?
x1a4
Not that I'm aware of, only add ons installed are Warden, Devise and CanCan...
Ola Tuvesson
A: 

It is a bug, but alas no prize:

https://rails.lighthouseapp.com/projects/8994/tickets/3087

Ola Tuvesson