首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >操作视图::错过模板-缺少模板消息/显示

操作视图::错过模板-缺少模板消息/显示
EN

Stack Overflow用户
提问于 2015-03-13 15:31:19
回答 1查看 2.5K关注 0票数 0

我有下面的errors_controller.rb

代码语言:javascript
复制
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发出请求时,它会给我

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

我不想做

代码语言:javascript
复制
rescue_from(ActionController::MissingTemplate)

因为这将处理所有操作丢失的模板错误,即使在url中有一些拼写错误。

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

尝试

我尝试添加了一个before_filter,但仍然给出了同样的错误。

我在application.rb中添加了application.rb,仍然没有运气。

有人能用这个给我指明方向吗?提前谢谢你

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-13 16:04:28

你可以:

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29036217

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档