简体   繁体   English

与活动模型序列化程序的复杂关联

[英]complex associations with active model serializer

For the sake of simplicity I've written this question as if writing a blog application but in actual fact it's an entirely different application. 为了简单起见,我已经像编写博客应用程序一样写了这个问题,但实际上它是一个完全不同的应用程序。 I have a show action similar to this in my users_controller.rb. 我的users_controller.rb中有一个与此类似的表演动作。

   def show 
      @user = User.find(params[:id])
      @posts = @user.posts   
    respond_to do |format|
      format.html
      format.json { render json: @user }
    end 
   end

Each post also has many comments . 每个post也有很多comments If I wanted to show all of the user posts and comments on those posts ( regardless of which user made the comment ), in the views/user/show.html.erb , it's fairly easy to access those comments from the obvious association between posts and comments. 如果我想显示所有用户帖子和这些帖子的评论( 无论是哪个用户发表评论 ),则在views/user/show.html.erb ,可以很容易地从帖子之间的明显关联中访问这些评论。和评论。

<% for post in @posts %>

<% post.comments.each do |c| %>

...

That will give me all the comments on those posts, not just the comments the user made, which is what I want. 这将为我提供这些帖子的所有评论,而不仅仅是用户发表的评论,这就是我想要的。

Now, I'm using active model serializer in this application, and in the User serializer, I can declare the association with posts has_many :posts , and then if I go to localhost:3000/user/1.json, I see the user details and the posts. 现在,我在此应用程序中使用活动模型序列化程序,并且在用户序列化程序中,我可以声明与posts has_many :posts的关联,然后如果我转到localhost:3000 / user / 1.json,我会看到用户详细信息和帖子。 However, I can't declare has_many :comments unless I only want the comments that that user made. 但是,除非我只想要该用户发表的评论,否则我不能声明has_many :comments However, I want all the comments on those posts regardless of the user who made them. 但是,无论发布者是谁,我都希望对这些帖子发表所有评论。

How could I achieve this with active model serializer? 如何使用主动模型序列化器实现此目标?

You could create a new serializer for Posts that includes all comments: 您可以为包含所有评论的帖子创建一个新的序列化器:

class FullPostSerializer < ActiveModel::Serializer

  has_many :comments

  def comments
    object.comments
  end

end

Then use the FullPostSerializer in your User serializer: 然后在您的用户序列化程序中使用FullPostSerializer:

has_many :post, serializer: FullPostSerializer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM