Add the ActiveModelSerializers
gem to your Gemfile.
Expose the desired API endpoints. If we want to expose a lot of data, we can use a controller wildcard.
Since this will match some paths that we don't want to expose or aren't valid routes (e.g. /sessions/1/data
), and since all our controllers inherit from ApplicationController
, we can add some default behavior to keep things safe.
Now we can override the default action in our respective controllers, as well as add two additional actions in our users controller.
Rails already has an instance.to_json
method via ActiveRecord::Serialization
, but the Serializers gem we added allows us to define our own custom serializers. This way, we can serve exactly the data we want through our API, rather than ALL the model's data.
Serializers are defined very similarly to Models, and ActiveModelSerializers
automatically nests associated models one level deep. Additionally we can define custom attributes to send with our data.
In this case a Review
does not have a medium_title
attribute, but when accessing review data via our API, we'll need to know which medium was reviewed. Note that object
, in our medium_title
accessor, is the current object being serialized.
Similarly the View
does not have a title
attribute, but it is useful to know when it is accessed via the API.
Now this data is readily available at our specified endpoints.
View the source on GitHub.
Ruby on Rails Web App pt 2 - Routing|Consuming your Rails API with React/Redux