简体   繁体   中英

Override as_json method in rails

I am trying to buid a blog app using rails api in backend and angular js in frontend. In my app every post has many comments and every comment has many replies. I have made one to many relationship between post and comment and comment and replies. When I click on a post title it takes me to a post show page using PostController#show method with it's comment. For this in Post model I have override as_json method like this:

class Post < ActiveRecord::Base
  has_many :comments

  def as_json(options = {})
    super(options.merge(include: :comments))
  end
end

But I want to show all replies with the comment. For this how can I modify as_json method?

You can try this

posts.as_json(include: { comments: {
                           include: { replies: {
                                          only: :body } },
                           only: :title } })

Ref

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