How to Return Http 204 in a Rails Controller

How to return HTTP 204 in a Rails controller

head :no_content

Tested with Rails 3.2.x, 4.x. It causes the controller method to respond with the 204 No Content HTTP status code.

An example of using this inside a controller method named foobar:

def foobar
head :no_content
end

Ruby On Rails Error 204 generate an image into a new view from controller

To render raw binary data (such as an image) from a controller, use send_data:

send_data(image.to_s, type: 'image/png', disposition: 'inline')

I recommend generating your QR code in a private method, then rendering that from your controller action:

class BeneficiosController < ApplicationController
require 'rqrcode'

def generate_qrcode
qrcode = make_qrcode
send_data qrcode.to_s, type: 'image/png', disposition: 'inline'
end

private

def make_qrcode
qrcode = RQRCode::QRCode.new('ejemplo')
image = qrcode.as_png(
resize_gte_to: false,
resize_exactly_to: false,
fill: 'white',
color: 'black',
size: 120,
border_modules: 4,
module_px_size: 6,
file: nil # path to write
)
image.resize(150, 150)
end
end

Override 204 status code message

HTTP 204 is NOT error response. 204 is used when response was successful and content body is intentionally empty.

From: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

The server has fulfilled the request but does not need to return an
entity-body, and might want to return updated metainformation. The
response MAY include new or updated metainformation in the form of
entity-headers, which if present SHOULD be associated with the
requested variant.

If the client is a user agent, it SHOULD NOT change its document view
from that which caused the request to be sent. This response is
primarily intended to allow input for actions to take place without
causing a change to the user agent's active document view, although
any new or updated metainformation SHOULD be applied to the document
currently in the user agent's active view.

The 204 response MUST NOT include a message-body, and thus is always
terminated by the first empty line after the header fields.

In this particular situation, 404 looks like more suitable.

More here: http://benramsey.com/archives/http-status-204-no-content-and-205-reset-content/



Related Topics



Leave a reply



Submit