Active Model Serializer发送has_many的父级

时间:2015-02-20 08:26:36

标签: ruby-on-rails active-model-serializers

在我的评论控制器中,我序列化了评论。当我在序列化程序中放置belongs_to :post_id时,每个评论都有一个帖子,但由于所有这些评论都来自同一篇文章,因此它是多余的。我知道我可以使用带有has_many注释的post序列化程序,但是因为我在评论控制器中看起来并不是惯用的。我怎么做到这一点?

希望:{ comments: { ... }, post: { ... } }

1 个答案:

答案 0 :(得分:1)

如果要防止多余包含关联,请设置embed

embed :objects               # Embed associations as full objects
embed :ids                   # Embed only the association ids
embed :ids, :include => true # Embed the association ids and include objects in the root

所以

class Comments < ActiveModel::Serializer
  embed :ids, include: true
end

只会在最高级别包含一次帖子:

{
  comments: [
    {
      id: 1,
      text: "Foo",
      post_id: 1
    },
    {
      id: 2,
      text: "Bar",
      post_id: 1
    }
  ],
  posts: [
    {
      id: 1,
      title: "Lorem ipsum"
    }
  ]
}

如果你想根据情况完全包含或遗漏关联,this wonderful StackOverflow answer通过(ab)使用预先加载来提供一个很好的解决方案:

class Comments < ActiveModel::Serializer
  attributes :id, :text, :poster_id

  belongs_to :poster

  def include_poster?
    object.association(:poster).loaded?
  end

  def include_poster_id?
    !include_poster?
  end
end

现在,通过清除post关联,您可以阻止它被包含在内:

@comments = @post.comments
@comments.post.reset

respond_with @comments

相反,显式急切加载关联将包含它:

@comments = Comment.includes(:poster).order(id: :asc).limit(10)
respond_with @comments