125

私は 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」という名前の空のテキスト ファイルをダウンロードします。

何を与える?

4

2 に答える 2

279

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

ただし、呼び出しは、 HTTP ヘッダーのみを生成することが明示されているため、呼び出しheadのより明白な代替手段となります。render :nothing


  1. http://guides.rubyonrails.org/layouts_and_rendering.html#using-head-to-build-header-only-responses
于 2013-08-05T13:46:58.147 に答える
147

UPDATE: This is an old answer for legacy Rails versions. For Rails 4+, see William Denniss' post below.

Sounds to me like the content type of the response isn't correct, or isn't correctly interpreted in your browser. Double check your http headers to see what content type the response is.

If it's anything other than text/html, you can try to manually set the content type like this:

render :nothing => true, :status => 200, :content_type => 'text/html'
于 2011-01-08T04:26:37.580 に答える