2014-11-24 65 views
1

我用JBuilder中創建我的API的觀點,但許多方法共享相同的JBuilder文件相同的模板:的Rails:respond_with兩種方法

module API 
    module V1 
    class DevicesController < ActionController::Base 

    respond_to :json 

    def create 
     ... 
     respond_with @device, status: 201 
    end 

    def update 
     ... 
     respond_with @device, status: 200 
    end 

    end 
end 

在本例中波紋管,createupdate方法分享相同的觀點:device_response.json.jbuilder。我嘗試了respond_to :json後添加template "devices/device_response",但我得到以下幾點:

undefined method `template' for API::V1::DevicesController:Class 

我如何可以定義兩種方法獨特的JBuilder的模板迴應?

謝謝。

+2

我想給'respond_with'方法應該是一個散列:'respond_with @device,狀態:200,模板: 「設備/ device_response」' – 2014-11-24 11:27:03

+0

但我的文檔發現,'respond_with'不以模板作爲參數 – 2014-11-24 12:23:03

回答

4

respond_with不需要template作爲參數。對於呈現相同的模板,你可以使用例如:

def create 
    # ...... 
    respond_with(@device, status: 200) do |format| 
    if @device.save 
     format.json { redirect_to @device } 
    else 
     format.json { render 'devices/device_response' } 
    end 
    end 
end 

爲什麼工作respond_with(*resources, &block)

如果是可接受的格式不被識別,應用程序將返回一個 「406 - 不接受」狀態。否則,默認響應是以 呈現以當前動作和所選 格式命名的模板。 index.html.erb。如果沒有模板可用,則該行爲 取決於所選擇的格式:

  • 一個HTML的響應 - 如果請求方法得到的,一個例外是 提出,但其他請求如發佈響應取決於 資源是否有任何驗證錯誤(即假設一個 已嘗試保存資源,例如通過創建行動)

    • 如果沒有錯誤,即RESO urce被成功保存,響應重定向到資源,即其顯示操作。

    • 如果存在驗證錯誤,響應會呈現一個默認操作,即對於發佈請求爲new:對修補程序或put進行編輯。