I am using the JSONAPI format along with Active Model Serializers to create an api with rails-api.
I have a serializer which shows a specific post
that
Instead of defining topics method, it's better to define separate topic serializer with explicitly specifying which attributes do you need to include. This is cleaner, and more maintainable approach then defining topics method.
class PostSerializer < ActiveModel::Serializer
attributes :title
belongs_to :domain
belongs_to :user
# remember to declare TopicSerializer class before you use it
class TopicSerializer < ActiveModel::Serializer
# explicitly tell here which attributes you need from 'topics'
attributes :title
end
has_many :topics, serializer: TopicSerializer
end
Again, try to avoid defining methods for relations as much as possible, it's not clean, neither maintainable.
Just make sure to return a hash or array of hashes like so:
def videos
object.listing_videos.collect do |lv|
{
id: lv.video.id,
name: lv.video.name,
wistia_id: lv.video.wistia_id,
duration: lv.video.duration,
wistia_hashed_id: lv.video.wistia_hashed_id,
description: lv.video.description,
thumbnail: lv.video.thumbnail
}
end
end