【问题标题】:What does respond_to do?respond_to 做什么?
【发布时间】:2013-03-21 07:52:20
【问题描述】:
#some instance variables
respond_to do |format|
  format.html
  format.xml {...}
  format.json {...}
end

respond_to 是简单地将所有实例变量发送到下一个网页还是做更多的事情?

我想知道 respond_to 会发送多少数据。例如,如果我有很多实例变量@one @two @three 等等。它们都是由respond_to 发送的吗?是否还会捆绑并发送任何其他数据? ?

【问题讨论】:

  • 不,这不是我要问的。我想知道 respond_to 会发送多少数据。
  • “发送”是什么意思? “捆绑”是什么意思?你想达到什么目的?

标签: ruby-on-rails


【解决方案1】:

Rails 会遍历注册的格式并尝试找到兼容的格式,否则会引发错误。

例子:

def index
  @stories = Story.all
end

index 操作没有 respond_to 块。如果客户端要求获取 TEXT 格式的页面,会导致如下异常:

ActionView::MissingTemplate (Missing template blogs/index ... with { ... :formats=>[:text], ...})

我们可以通过添加respond_to 块轻松解决​​此问题:

def index
  @stories = Story.all

  respond_to do |format|
    format.html
    format.js 
  end
end

更改后,当格式不支持时,客户端会得到406 error。此外,您的索引操作将响应两种新格式:j​​s 和 HTML。

本文介绍了您可以使用respond_to blocks 的所有方式。

【讨论】:

    【解决方案2】:

    没有您的指示,您的实例变量不会被发送到任何地方。

    您可能有一个 .html.erb 模板,它在收到 HTML 请求时呈现实例变量 (format.html)。

    对于 xml 和 json 响应,您需要告诉 Rails 要做什么。例如,您可以提供模板 .xml.builder。 Rails 还可以自动为您渲染某些结构(数组等),只需调用render json: @one

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-11
      • 2016-08-30
      • 1970-01-01
      • 2014-04-29
      • 1970-01-01
      • 2020-07-08
      • 2016-04-30
      • 1970-01-01
      相关资源
      最近更新 更多