Customize JSON in the Models Themselves
Learn how to customize the JSON in the models.
We'll cover the following...
Optimizing the JSON
Suppose we wanted our widget’s API to use the JSON encoding we showed above. We could certainly achieve this in our controller like so:
def show
widget = Widget.find(params[:id])
render json: {
widget: widget.as_json(
methods: [ :user_facing_identifier ],
except: [ :widget_status_id ],
include: [ :widget_status ]
)
}
end
Of course, if we need to implement the index
method, that code would want to use the same options. We could create a private method in Api::V1::WidgetsController
called ...