Overriding as_json has no effect?
- by Ola Tuvesson
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?