Created
June 14, 2018 21:27
-
-
Save cswalina/5f04c41dfc4eb017e8ed5ec340e30557 to your computer and use it in GitHub Desktop.
Rails API 2 ways: active_model_serializers, fast_jsonapi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
gem 'active_model_serializers' | |
rails g serializer publication | |
app/serializers/api/v1/publication_serializer.rb | |
module API::V1 | |
class PublicationSerializer < ActiveModel::Serializer | |
attributes :title | |
end | |
end | |
app/controllers/api/v1/publications_controller | |
module API::V1 | |
class PublicationsController < APIController | |
def index | |
render json: Publication.all, each_serializer: API::V1::PublicationSerializer | |
end | |
end | |
end | |
--------------------------------------------------------------------------------------------------- | |
gem 'fast_jsonapi' | |
rails g serializer publication | |
app/serializers/api/v1/publication_serializer.rb | |
module API::V1 | |
class PublicationSerializer | |
include FastJsonapi::ObjectSerializer | |
attributes :title | |
end | |
end | |
app/controllers/api/v1/publications_controller | |
module API::V1 | |
class PublicationsController < APIController | |
def index | |
render json: API::V1::PublicationSerializer.new(Publication.all).serialized_json | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment