Active Model Serializers嵌套关联,使用参数调用方法

时间:2017-11-16 12:53:24

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

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

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

这不起作用..任何人都能帮助我吗?

1 个答案:

答案 0 :(得分:3)

在序列化程序实例

上调用.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