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

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

大部分 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 都只支持指定的请求类型。但不推荐这中写法,原因有二:

需要在 action 中结合 response_with 使用
限制了这个控制器只能处理指定某种类型的请求,不灵活

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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值