How do I select which attributes I want for active model serializers relationships

后端 未结 2 1222
梦毁少年i
梦毁少年i 2021-01-05 04:46

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

相关标签:
2条回答
  • 2021-01-05 05:31

    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.

    0 讨论(0)
  • 2021-01-05 05:38

    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
    
    0 讨论(0)
提交回复
热议问题