【问题标题】:Stop Rails from trying to provide a template / ActionView::MissingTemplate阻止 Rails 尝试提供模板 / ActionView::MissingTemplate
【发布时间】:2014-12-28 01:52:47
【问题描述】:

我有一个简单的 Angular Rails 应用程序,我正在尝试连接它。

这是我的 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语法吗?可以让我永远摆脱模板吗?

【问题讨论】:

    标签: ruby-on-rails json activerecord controller respond-with


    【解决方案1】:

    rails中有两种渲染方式,CMIIW

    首先,默认会渲染一个视图模板,例子

      def show
      end
    
    

    然后它将呈现默认的显示视图模板,例如: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
    

    不需要使用respond_to,它也已从最新的rails中删除

    关于render的rails指南非常有用,你可以阅读它here

    【讨论】:

    • 请注意:我相信 render json: @item.to_json 可以使用 Active Record 序列化器成为 render json: @item
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多