Suppose I have a Rails app with two models Post and Comment. A post has_many comments and a comment belongs_to a post.
How can I override the respond_to function in the show action in order to get a JSON response containing both the Post properties and an array of Comment objects that it has?
Currently it is the vanilla Rails default:
# posts_controller.rb
def show
@post = current_user.posts.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @post }
end
end
You can do that using Active Record serialization method.
to_json
Below code should work.
format.json { render json: @post.to_json(:include => :comments) }
Try using active_model_serializers for json serialization. It is easy to include associated objects and also separates things by having a different file for serialization.
Example:
class PostSerializer < ApplicationSerializer
attributes :id, :title, :body
has_many :comments
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With