【问题标题】:Active Model Serializers nested associations that calls methods with argumentsActive Model Serializers 嵌套关联调用带参数的方法
【发布时间】:2017-11-16 12:53:24
【问题描述】:

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

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

现在我希望活动模型序列化程序让我所有用户在某一天发布包含 cmets 的帖子,也包括这些 cmets。

我试过了,但我能得到的只是用户在某天发布了包含 cmets 的帖子..但我也无法包含 cmets。

我就是这么做的

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

  def day_posts
    object.posts_has_comments_in_certain_day(day)
  end
end

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

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

这不起作用..有人可以帮我吗?

【问题讨论】:

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


    【解决方案1】:

    在序列化程序实例上调用.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
    

    如果您需要自定义 cmets 属性,也可以为 cmets 做同样的事情。

    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
    

    【讨论】:

    • 对不起,我做错了..它现在完美无缺,谢谢伙计
    • 有没有办法序列化嵌套对象而不显式调用子序列化器?不得不手动做这样的事情似乎有点不方便
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    相关资源
    最近更新 更多