Ruby   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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

大佬总结

以上是大佬教程为你收集整理的ruby-on-rails – 阻止Rails尝试提供模板/ ActionView :: MissingTemplate全部内容,希望文章能够帮你解决ruby-on-rails – 阻止Rails尝试提供模板/ ActionView :: MissingTemplate所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。