"render:nothing => true"返回空的纯文本文件?

use*_*643 114 rest ruby-on-rails link-to

我在Rails 2.3.3上,我需要创建一个发送帖子请求的链接.

我有一个看起来像这样的:

= link_to('Resend Email', 
  {:controller => 'account', :action => 'resend_confirm_email'}, 
  {:method => :post} )
Run Code Online (Sandbox Code Playgroud)

这会在链接上产生适当的JavaScript行为:

<a href="/account/resend_confirm_email" 
  onclick="var f = document.createElement('form'); 
  f.style.display = 'none'; 
  this.parentNode.appendChild(f); 
  f.method = 'POST'; 
  f.action = this.href;
  var s = document.createElement('input'); 
  s.setAttribute('type', 'hidden'); 
  s.setAttribute('name', 'authenticity_token'); 
  s.setAttribute('value', 'EL9GYgLL6kdT/eIAzBritmB2OVZEXGRytPv3lcCdGhs=');
  f.appendChild(s);
  f.submit();
  return false;">Resend Email</a>'
Run Code Online (Sandbox Code Playgroud)

我的控制器操作正在运行,并设置为不渲染:

respond_to do |format|
  format.all { render :nothing => true, :status => 200 }
end
Run Code Online (Sandbox Code Playgroud)

但是当我点击链接时,我的浏览器会下载一个名为"resend_confirm_email"的空文本文件.

是什么赋予了?

Wil*_*iss 251

自Rails 4以来,head现在更受欢迎render :nothing.1

head :ok, content_type: "text/html"

# or (equivalent)

head 200, content_type: "text/html"
Run Code Online (Sandbox Code Playgroud)

比...更受欢迎

render nothing: true, status: :ok, content_type: "text/html"

# or (equivalent)

render nothing: true, status: 200, content_type: "text/html"
Run Code Online (Sandbox Code Playgroud)

它们在技术上是相同的.如果您查看使用cURL的响应,您将看到:

HTTP/1.1 200 OK
Connection: close
Date: Wed, 1 Oct 2014 05:25:00 GMT
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8
X-Runtime: 0.014297
Set-Cookie: _blog_session=...snip...; path=/; HttpOnly
Cache-Control: no-cache
Run Code Online (Sandbox Code Playgroud)

但是,调用head提供了一个更明显的调用替代方法,render :nothing因为它现在明确表示您只生成HTTP标头.


  1. http://guides.rubyonrails.org/layouts_and_rendering.html#using-head-to-build-header-only-responses

  • `head 200`对我来说是一个'304`响应(在rails 4.1.6上).控制台显示200状态代码,但chrome(网络面板)显示304.`renplay:nothing => true`方法有效. (2认同)
  • 如果只返回标题,是否需要内容类型? (2认同)

von*_*rad 142

更新:这是旧版Rails版本的旧答案.对于Rails 4+,请参阅下面的William Denniss的帖子.

听起来像响应的内容类型不正确,或者在浏览器中没有正确解释.仔细检查您的http标头,看看响应的内容类型.

如果它不是text/html,您可以尝试手动设置内容类型,如下所示:

render :nothing => true, :status => 200, :content_type => 'text/html'
Run Code Online (Sandbox Code Playgroud)