[英]Getting nested JSON output from Rails
假設我有一個帶有兩個模型Post
和Comment
的Rails應用程序。 帖子has_many
評論和評論belongs_to
帖子。
如何覆蓋show
動作中的respond_to
函數以獲取包含Post
屬性和它具有的Comment
對象數組的JSON響應?
目前它是vanilla Rails的默認值:
# 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
您可以使用Active Record序列化方法執行此操作。
to_json
下面的代碼應該工作。
format.json { render json: @post.to_json(:include => :comments) }
嘗試使用active_model_serializers進行json序列化。 包含關聯對象很容易,並且通過使用不同的序列化文件來分隔事物。
例:
class PostSerializer < ApplicationSerializer
attributes :id, :title, :body
has_many :comments
end
Rails提供了最好的響應方式:
在控制器頂部定義respond_to 。 喜歡 :
class YourController < ApplicationController
respond_to :xml, :json
def show
@post = current_user.posts.find(params[:id])
respond_with (@post)
end
end
欲了解更多信息,請訪問: http : //davidwparker.com/2010/03/09/api-in-rails-respond-to-and-respond-with/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.