在Active Model Serializer中自定义has_many,belongs_to嵌套关联json

时间:2016-11-28 10:12:16

标签: json ruby-on-rails-5 active-model-serializers rails-api

我该怎么做

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

1 个答案:

答案 0 :(得分:0)

你可以这样做,但使用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