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?
Some further testing, in the controller action:
And in the model:
Outputs:
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:
in my controller action, and the below in the model, the override works:
Outputs...
...which is the expected output. Have I found a bug? Do I win a prize?
It is a bug, but alas no prize:
https://rails.lighthouseapp.com/projects/8994/tickets/3087