2016-12-17 4 views
0

私はAPIのみのRails 5アプリを持っています。Rails 5はJSONをレンダリング用にレンダリングしません

私customers_controller_testは、私は理由を理解することはできません

ActionView::MissingTemplate: Missing template api/v1/customers/show, application/show with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :jbuilder] 

で失敗します。

コントローラはこのようになります(足場)

# POST /customers 
    # POST /customers.json 
    def create 
    @customer = Customer.new(customer_params) 

    if @customer.save 
     render :show, status: :created, location: api_v1_customer_url(@customer) 
    else 
     render json: @customer.errors, status: :unprocessable_entity 
    end 
    end 

    # PATCH/PUT /customers/1 
    # PATCH/PUT /customers/1.json 
    def update 
    if @customer.update(customer_params) 
     render :show, status: :ok, location: api_v1_customer_url(@customer) 
    else 
     render json: @customer.errors, status: :unprocessable_entity 
    end 
    end 

なぜPOSTリターンHTMLはPUTが正しくJSONを返すときですか?

テストでは、この変更に細かい渡し:

# POST /customers 
    # POST /customers.json 
    def create 
    @customer = Customer.new(customer_params) 

    if @customer.save 
     render json: 'show', status: :created, location: api_v1_customer_url(@customer) 
    else 
     render json: @customer.errors, status: :unprocessable_entity 
    end 
    end 

はそれを説明することができ、誰ですか?

+0

:http://stackoverflow.com/a/6519357/1062276 – ringe

答えて

0

あなたのコードは、テンプレート

def create 
    customer = Customer.new(customer_params) 
    respond_to do |format| 
    format.json do 
     if customer.save 
     render json: customer, status: :created, , location: api_v1_customer_url(@customer 
     else 
     render json: customer.errors, status: :unprocessable_entity 
     end 
    end 
    end 
end 
+0

あなたのAPIがJSONだけを扱う必要があるなら、あなたは 'respond_to'と' format.json'のものを取り除くことができます –

1

エラーの原因をレンダリングしようとしているが、このライン上にある:render(:show)を呼び出す

render :show, status: :created, location: api_v1_customer_url(@customer) 

は「ショー」テンプレートを探すためにレールを教えてくれますし、それをレンダリングする。 Railsはそのテンプレートを探していて見つからないので、エラーが発生します。

Antarrの答えは良い解決策を提供します。あなたの状況については、APIの複数の応答形式をサポートしているとは思えないので、私は以下のように簡略化します。私はそれを行うことになっているものはよく分からないので

def create 
    customer = Customer.new(customer_params) 
    if customer.save 
    render json: customer, status: :created 
    else 
    render json: customer.errors, status: :unprocessable_entity 
    end 
end 

注私もlocationパラメータを取り出した

デフォルトの書式を設定する方法についてのこのコメントは私の問題を解決し
+0

"ショー"テンプレートはjbuilderのものです。しかし、なぜそれが更新で失敗しないのですか? – ringe

+0

hmm ... * show.json.jbuilderテンプレートがあり、見つからない場合、デフォルトのフォーマットはhtmlで、レールはhtmlテンプレートを探しています。これは、上記のあなたのコメントを参照するために、jsonにデフォルトフォーマットを設定することがあなたの問題を解決した理由を説明します –

関連する問題