简体   繁体   中英

NoMethodError: undefined method `pages' for # Array when use as_json

I know that this is a answered question, but today as I setup a simple map over a array this issue comes again!

the map unlike the common way to do it is using as_json

 def index
    @allcomments = @commentable.comments.order('created_at desc')
    .includes(:user,:replies).paginate page: params[:page]

    @comments = @allcomments.map do |comment|
      comment_json = comment.as_json
      comment_json[:user] = comment.user.as_json
      comment_json[:replies] = comment.replies.as_json
      comment_json
    end

    render json: {
      comments: @comments.paginate(page: page),
      page: page,
      pages: @comments.pages,
      status: 200
    }
  end

As the answer should be place require 'will_paginate/array' on the initializer, I did, or on the ApplicationController , I did too, or on the comments controller I did it too!

So, someone has any clue about this particular issue with will_paginate ?

When you apply map you yield a raw array which loses the pagination features. You need to preserve that.

One thing you could do here to fix this is to write a as_json method for Comment that properly implements the logic you have in that map , handling the user and replies encoding correctly. The goal here is to get rid of that step in the controller, move that to the model where it belongs.

Then this becomes:

@comments = @commentable.comments.order('created_at desc')
  .includes(:user,:replies).paginate(page: params[:page])

paginated = @comments.paginate(page: page)

render(json: {
  comments: paginated,
  page: page,
  pages: paginated.pages,
  status: 200
})

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