Overriding as_json has no effect?
Posted
by Ola Tuvesson
on Stack Overflow
See other posts from Stack Overflow
or by Ola Tuvesson
Published on 2010-05-27T21:01:12Z
Indexed on
2010/05/28
2:41 UTC
Read the original article
Hit count: 389
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?
© Stack Overflow or respective owner