Rails 使用 response_to 渲染视图的必要性

作者: 老码农不上班 | 来源:发表于2016-07-26 01:55 被阅读480次

大部分 Rails 开发者觉得如果控制器中的 action 仅仅是渲染 HTML 模版,没必要使用 respond_to。Rails 脚手架(scaffold)生成的代码也是如此,不使用 response_to

class PostsController < ApplicationController
  def index
    @posts = Post.all
  end
end

然而,如果有用户恶意请求 XML 格式时,会导致程序报错。你可以自己试试:

curl -H "Accept: application/xml" localhost:3000/posts

程序会报如下错误:

Missing template posts/index, ... :formats=>[:xml]

请求的客户端会看到 500 ,表明程序内部出现错误。

<?xml version="1.0" encoding="UTF-8"?>
<hash>
  <status>500</status>
  <error>Internal Server Error</error>
</hash>

这些异常信息会被 Rails 记录下来,随着你的网站访问量达到一个量级,各种请求格式都会出现。我们并不希望每次这样没意义的错误日志出现。那么如何避免这种情况呢。
使用 response_to ,表明这个 action 只会支持指定类型的请求

class PostsController < ApplicationController
  def index
    @posts = Post.all
    respond_to do |format|
      format.html
    end
  end
end

同时,你也可以在 action 的外部,指明这个控制器内所有的 action 都只支持指定的请求类型。但不推荐这中写法,原因有二:

  1. 需要在 action 中结合 response_with 使用
  2. 限制了这个控制器只能处理指定某种类型的请求,不灵活
class PostsController < ApplicationController
  respond_to :html

  def index
    @posts = Post.all
    respond_with @posts
  end
end

使用 response_to ,客户端请求 action 不支持的相应类型,会收到 406 错误而不是 500

<?xml version="1.0" encoding="UTF-8"?>
<hash>
  <status>406</status>
  <error>Not Acceptable</error>
</hash>

推荐阅读:
respond_to Without All the Pain

相关文章

  • Rails 使用 response_to 渲染视图的必要性

    大部分 Rails 开发者觉得如果控制器中的 action 仅仅是渲染 HTML 模版,没必要使用 respond...

  • Rails视图渲染

    在 MVC 架构中**控制器的作用是处理请求(request),但经常会把繁重的操作交给模型完成。返回响应(res...

  • Rails布局(layout)

    Rails 渲染响应的视图时,会把视图和当前模板结合起来。 1. 查找布局 默认布局 查找布局时,Rails首先查...

  • Rails布局和视图渲染

    创建响应 从控制器的角度,创建HTTP响应有三种方法: 调用 render 方法 调用 redirect_to 方...

  • Rails渲染视图时的约定

    基于约定在routes中配置了 resources :posts class PostsController < ...

  • 前端性能优化(蛋人网)

    01 前端性能优化介绍02 网页性能优化03 浏览器的加载和渲染机制04 如何在Rails的视图layout中放置...

  • rails布局和视图

    渲染顺序以及继承 渲染页面的时候使用模版 在rails中可以通过指定layout的方式设置不同的控制器使用的布局文...

  • 深入浅出vue.js

    渐进式框架 视图层渲染-组件机制-路由机制-状态管理-构建工具你可以使用只使用视图层渲染快速开发,也可以使用全家桶...

  • 【Metal】使用Metal绘制视图的内容(II)

    创建MetalKit视图和渲染过程以绘制视图的内容 下载 概观 在本示例中,您将学习使用Metal渲染图形内容的基...

  • android-opengles3.0开发【1】基本使用

    简介 android 中使用 opengles 基本思路: 使用 GLSurfaceView 作为显示渲染的视图;...

网友评论

    本文标题:Rails 使用 response_to 渲染视图的必要性

    本文链接:https://www.haomeiwen.com/subject/fernjttx.html