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

时间:2011-01-08 04:04:07

标签: ruby-on-rails rest link-to

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

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

= link_to('Resend Email', 
  {:controller => 'account', :action => 'resend_confirm_email'}, 
  {:method => :post} )

这会在链接上产生适当的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>'

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

respond_to do |format|
  format.all { render :nothing => true, :status => 200 }
end

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

是什么给出了?

2 个答案:

答案 0 :(得分:242)

自Rails 4以来,head现在优先于render :nothing 1

head :ok, content_type: "text/html"

# or (equivalent)

head 200, content_type: "text/html"

优先于

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

# or (equivalent)

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

它们在技术上是相同的。如果您查看使用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

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


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

答案 1 :(得分:141)

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

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

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

render :nothing => true, :status => 200, :content_type => 'text/html'