簡體   English   中英

從Rails獲取嵌套的JSON輸出

[英]Getting nested JSON output from Rails

假設我有一個帶有兩個模型PostComment的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

您可以在模型中覆蓋to_json ,也可以使用Jbuilderrabl

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM