HEAD HTTP Requests in Rails 3

Rails 3 is currently sending a HEAD request to the corresponding GET route. Have a head? The method is on request, but returns false, and the request acts like a get request. Can I determine if a request is a HEAD request?

Reasoning: I get that the HEAD request should return the EXACT same headers as get, so Rails wants to execute a full GET and then shave off the body. However, I can match this query without causing the same DB calls, etc., that GET. It makes sense?

+6
source share
3 answers

I had this exact problem. It turns out that this makes caching possible. Enable caching in your environment and #head? will work as expected.

The problem is that Rack :: Cache turns HEAD requests into GET requests so that they can be cached. This is probably the correct behavior, but it interfered with my application.

+4
source

Can you use request.head? method to find out if it is a HEAD request:

http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-head-3F

Once you have determined that this is the case, you can also use the head () method of the controller instead of the usual render:

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

So, I just checked request.head? before you worry about database activity. Then use

head :ok, :custom_header => 'value' 
+2
source
 def index if request.head? head :created else Rails.logger.info "Derp #{request.method}" end end 

Hm. The above controller method works as I would expect on Ruby v1.9.3-p194 and Rails v3.2.3; 201 without response body for HEAD requests and 200 w / for GET.

+1
source

Source: https://habr.com/ru/post/914842/


All Articles