Ruby on rails Rails 5不为create呈现JSON

Ruby on rails Rails 5不为create呈现JSON,ruby-on-rails,json,ruby-on-rails-5,Ruby On Rails,Json,Ruby On Rails 5,我有一个只有API的Rails 5应用程序 我的客户\u控制器\u测试失败 ActionView::MissingTemplate: Missing template api/v1/customers/show, application/show with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :jbuilder]

我有一个只有API的Rails 5应用程序

我的客户\u控制器\u测试失败

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

控制器看起来像这样(脚手架)

那么,当PUT正确返回JSON时,POST为什么返回HTML呢

通过此更改后,测试可以顺利通过:

  # 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

有人能解释吗?

您的代码正在尝试呈现模板

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

错误的原因在这一行:

render :show, status: :created, location: api_v1_customer_url(@customer)
调用
render(:show)
将告诉rails查找“show”模板并进行渲染。Rails正在查找该模板,但找不到它,因此引发了一个错误

Antar的答案提供了一个很好的解决方案。对于您的情况,我将简化为以下内容,因为我怀疑您的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
参数,因为我不确定它应该做什么

如果你的API只需要处理JSON,你可以去掉
respond\u to
format.JSON
填充“show”模板是一个jbuilder模板。但是为什么它在更新时不失败呢?嗯。。。如果有show.json.jbuilder模板,但找不到,那么我猜默认格式是html,rails正在寻找html模板。这就解释了为什么将默认格式设置为json解决了您的问题,请参考上面的注释。关于如何设置默认格式的注释解决了我的问题:
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