Generators
For New Resources: Rails Resources Generator
$ rails g resource post title:string body:string
This will generate a serializer at the same time in app/serializers/post_serializer.rb
for your new model.
For Existing Models: Serializer Generator
$ rails g serializer post
- Generated serializer will contain existing model's
attributes
and any has_many
,has_one
andbelongs_to
associations in the model. For example:
class PostSerializer < ActiveModel::Serializer
attributes :title, :body
has_many :comments
has_one :author
end
and
class CommentSerializer < ActiveModel::Serializer
attributes :name, :body
belongs_to :post_id
end
- Attribute names are a whitelist of attributes to be serialized
If generated associations are left, as per default, then serializing any record (e.g. a
post
) will include all those associations (e.g.comments
) if they- exist for that specific record (e.g. that
post
actually has any savedcomment
) - have serializers that can be found
- exist for that specific record (e.g. that
For more information, see Serializers.