ActionView :: MissingTemplate -----缺少模板消息/显示

时间:2015-03-13 15:31:19

标签: ruby-on-rails ruby actionview missing-template

我有以下errors_controller.rb

class ErrorsController < ActionController::Base
layout 'bare'

def show
return render_error params[:id], :ok
end

def index
  request.format.to_s.downcase == 'application/json' ? json_error : html_error
  return
end

private

def exception
  env['action_dispatch.exception']
end

def html_error
  if exception.nil?
    render_error 404
  else
    render_error 500
  end
end

def json_error
  if exception.nil?
    render json: error_hash(:resource_not_found), status: 404
  else
    render json: error_hash(:internal_server_error), status: 500
  end
end

def error_hash(code)
  {
    errors: [
      {
        message: I18n.t("errors.api.#{code}"),
        code: code
      }
    ]
  }
end

def render_error(code, status_type = nil)
  @error = ErrorMessage.new(code, status_type)
  render @error.partial, status: @error.status
end
end

向/api/test.xml发出请求时 它给了我

ActionView::MissingTemplate at /api/test.xml
Missing template messages/show with {:locale=>[:en], :formats=>[:xml],       :handlers=>[:erb, :builder, :raw, :ruby, :haml]}

我不想做

rescue_from(ActionController::MissingTemplate)

因为这将处理所有缺少模板错误的操作,即使网址中存在一些拼写错误。

我想要一种健康的方法来为任何请求抛出404(.xml,.jpeg,.....)

尝试

我尝试添加before_filter仍然给我同样的错误。

我在application.rb中添加了config.action_dispatch.ignore_accept_header = true,但仍然没有运气。

有人能告诉我这个方向吗?提前谢谢

1 个答案:

答案 0 :(得分:1)

你可以这样做:

def render_error(code, status_type = nil)
  @error = ErrorMessage.new(code, status_type)
  respond_to do |format|
    format.any(:html, :json) { render @error.partial, status: @error.status }
    format.any { head 404, "content_type" => 'text/plain' }
  end
end
相关问题