Since Rails 2.3.3, the best practice to take control over what attributes are exposed during a JSON serialization was to override the
as_json method as opposed to the
to_json method as it was done previously. The idea is that
as_json should return the object structure of the JSON (most likely a Hash) and
to_json encode that object into a JSON string. Jonathan Julian wrote a good reference post on that subject.
as_json method takes an
options hash that you can use to include/exclude certain attributes.
So let say you have a
Product model with
account_id as attributes. You don't want to expose the relationship to account and only include
created_at. You would override
as_json in your model as follows:
You can verify that it works in the Rails console:
Unfortunately, Rails 3.0 introduced a bug, where the
as_json method in the super class (ActiveRecord::Base) will just return the object and ignore the options passed. As a result in this case
to_json will output all the attributes contained in your model.
In the Rails 3.0.0 console, you get:
account_id is being included.
As a workaround, you can either hand-craft the attributes your want to return or use the following to simply output a hash:
Note that in these examples, the
ActiveRecord::Base.include_root_in_json setting was set to
false so that the root object class name is not included.