简体   繁体   中英

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.

   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 . 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.

<% 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. However, I can't declare has_many :comments unless I only want the comments that that user made. 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:

has_many :post, serializer: FullPostSerializer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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