阻止Rails尝试提供模板/ ActionView :: MissingTemplate

use*_*000 6 activerecord json controller ruby-on-rails respond-with

我有一个简单的角度轨道应用程序,我试图连线.

这是我的rails控制器:

class ItemsController < ApplicationController
  respond_to :json, :html

  def index
    @items = Item.order(params[:sort]).page(params[:page]).per(15)
  end

  def show
    @item = Item.where(params[:id])

    if @item.empty?
      flash[:alert] = "Item number #{params[:id]} does not exist"
    else
      respond_with @item do |format|
        format.json { render :layout => false }
      end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我一直收到ActionView::MissingTemplate错误,因为rails一直试图提供erb模板.我不想要模板!! 我只想要json.有人可以给出明确的respond_to/respond_with语法,这将永远摆脱我的模板吗?

Sai*_*Haq 8

rails中有两种渲染方式,CMIIW

首先,默认情况下,它将呈现视图模板,例如

  def show
  end

Run Code Online (Sandbox Code Playgroud)

然后它将呈现默认的显示视图模板,例如:app/views/controller_name/show.html.erb

第二种是通过手动渲染,使用render方法

如果你只想回应json,那么:

class ItemsController < ApplicationController
  def show
    id = params.require(:id)
    @item = Item.find_by(id: id)

    if @item.nil?
      render json: { message: "Item number #{id} does not exist", status: :not_found }
    else
      render json: @item
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

不需要使用respond_to,它也被从最新的轨道上删除了

rails guide about render非常有用,你可以在这里阅读