自定义has_many,属于Active Model Serializer中的嵌套关联JSON



我该怎么做

class UserSerializer < ApplicationSerializer
  attributes :id, :name. :email
  has_many :posts do                   # I don't want to use PostSerializer
    attributes :id, :title             # /posts/index would show more data
    has_many :comments do              # like created_at, updated_at, edits, other assocs..
      attributes: :id, :content
    end
  end
  belongs_to :category do              # I dont' want to user CategorySerializer
    attributes :id, :name              # /categories/index would show more data
  end                                  # like created_at, no. of users, associations, etc.,
end

您可以做这样的事情,但是使用serializers

class UserSerializer < ApplicationSerializer
  attributes :id, :name, :email, :user_posts
  def user_posts
    object.posts.map do |post|
      PostSerializer.new(post, only: [:id, :title])
    end
  end
end

最新更新