Active Model Serializers 嵌套关联调用带参数的方法

Active Model Serializers nested associations that calls methods with arguments

例如,如果我有这些关联的模型

class User 
  has_many :posts
  has_many :comments

  def posts_has_comments_in_certain_day(day)
    posts.joins(:comments).where(comments: { created_at: day })
  end 
end

class Post
  has_many :comments
  belongs_to :user

  def comments_in_certain_day(day)
    Comment.where(created_at: day, post_id: id)
  end
end

class Comment
  belongs_to :user
  belongs_to :post
end

现在,我希望活动模型序列化程序为我提供所有用户,他们的帖子在某一天有评论,也包括这些评论。

我试过了,但我只能得到他的帖子在某一天有评论的用户..但我不能也包含评论。

我就是这么做的

class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :day_posts

  def day_posts
    object.posts_has_comments_in_certain_day(day)
  end
end

这工作正常 但是当我尝试包含评论时! ..

class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :day_posts

  def day_posts
    object.posts_has_comments_in_certain_day(day).map do |post|
    PostSerializer.new(
      post,
      day: instance_options[:day]
    )
  end
end

class PostSerializer < ActiveModel::Serializer
  attributes :id, :body, :day_comments

  def day_comments
    object.comments_in_certain_day(day)
  end
end

这不起作用.. 谁能帮我解决这个问题?

在序列化程序实例上调用 .attributes

class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :day_posts

  def day_posts
    object.posts_has_comments_in_certain_day(day).map do |post|
    PostSerializer.new(
      post,
      day: instance_options[:day]
    ).attributes
  end
end

如果您需要自定义评论属性,也对评论做同样的事情。

class PostSerializer < ActiveModel::Serializer
  attributes :id, :body, :day_comments

  def day_comments
    object.comments_in_certain_day(day).map do |comment|
        CommentSerializer.new(comment).attributes
    end
  end
end