Skip to content

Instantly share code, notes, and snippets.

@between40and2
Created December 27, 2013 07:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save between40and2/8143850 to your computer and use it in GitHub Desktop.
Save between40and2/8143850 to your computer and use it in GitHub Desktop.
If you are not satisfied with default to_json implementation of ActiveRecord. Here is the way out.
Customizing a model object's JSON representation, first of all, is a business of ActiveRecord::Serialization. You will look at ActiveModel::Serializers::JSON class
https://github.com/rails/rails/blob/master/activemodel/lib/active_model/serializers/json.rb
and then will come back to ActiveModel::Serialization class
https://github.com/rails/rails/blob/master/activemodel/lib/active_model/serialization.rb
- Non-subclassing approach
configure as/to_json method such options of :only , :except: , and :include
- subclassing approach
You need to override (re-define) as_json method of your model class.
for any specific key/attribute, you can def read_attribute_for_serialization method
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment