ruby-on-rails – 阻止Rails尝试提供模板/ ActionView :: MissingTemplate

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 阻止Rails尝试提供模板/ ActionView :: MissingTemplate前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个简单的角度轨道应用程序,我试图连线.

这是我的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

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

解决方法

rails中有两种渲染方式,CMIIW

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

def show
结束

然后它将像往常一样渲染节目视图,
即使你声明了respond_to:json,它也会渲染json视图,这就是为什么你得到MissingTemplate异常

然后下一个方法是使用渲染json:…,例子

class ItemsController < ApplicationController
  respond_to :json,:html

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

    if @item.empty?
      render json: { message: "Item number #{params[:id]} does not exist",status: :not_found }
    else
      render json: @item.to_json
    end
  end
end

rails guide about render非常有用,你可以读它here

原文链接:https://www.f2er.com/ruby/264810.html

猜你在找的Ruby相关文章