What Does ':Location => ...' and 'Head :Ok' Mean in the 'Respond_To' Format Statement

What does `:location = ...` and `head :ok` mean in the 'respond_to' format statement?

  1. render ... :location => @user will set the HTTP location header to inform the client of the location of the newly created resource (that is, its URL)

  2. head :ok sets render to return an empty response (so just the header, no body) with status 200. head :ok is shorthand for render nothing: true, status: :ok.

    Here's a list of all the :status options you can use for setting the appropriate status code.

Override the respond_to format with form button in rails 3

I can finally respond to my own question, now. So here's the answer:

I figured out how this can be accomplished. You can set the name of the buttons to be "format" and set the value to the extension that you would append to the URL.

 <%= button_tag( 'HTML', :value => 'html', :name => 'format' ) %>
<%= button_tag( 'CSV', :value => 'csv', :name => 'format' ) %>
<%= button_tag( 'JSON', :value => 'json', :name => 'format' ) %>

Simply changing the params[:format] doesn't work. You have to pass it in before your action runs.

Rails: How does the respond_to block work?

I am new to Ruby and got stuck at this same code. The parts that I got hung up on were a little more fundamental than some of the answers I found here. This may or may not help someone.

  • respond_to is a method on the superclass ActionController.
  • it takes a block, which is like a delegate. The block is from do until end, with |format| as an argument to the block.
  • respond_to executes your block, passing a Responder into the format argument.

http://api.rubyonrails.org/v4.1/classes/ActionController/Responder.html

  • The Responder does NOT contain a method for .html or .json, but we call these methods anyways! This part threw me for a loop.
  • Ruby has a feature called method_missing. If you call a method that doesn't exist (like json or html), Ruby calls the method_missing method instead.

http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_2.html

  • The Responder class uses its method_missing as a kind of registration. When we call 'json', we are telling it to respond to requests with the .json extension by serializing to json. We need to call html with no arguments to tell it to handle .html requests in the default way (using conventions and views).

It could be written like this (using JS-like pseudocode):

// get an instance to a responder from the base class
var format = get_responder()

// register html to render in the default way
// (by way of the views and conventions)
format.register('html')

// register json as well. the argument to .json is the second
// argument to method_missing ('json' is the first), which contains
// optional ways to configure the response. In this case, serialize as json.
format.register('json', renderOptions)

This part confused the heck out of me. I still find it unintuitive. Ruby seems to use this technique quite a bit. The entire class (responder) becomes the method implementation. In order to leverage method_missing, we need an instance of the class, so we're obliged to pass a callback into which they pass the method-like object. For someone who has coded in C-like languages for 20 some years, this is very backwards and unintuitive to me. Not that it's bad! But it's something a lot of people with that kind of background need to get their head around, and I think might be what the OP was after.

p.s. note that in RoR 4.2 respond_to was extracted into responders gem.

rails respond_to format.js API

respond_to do |format|
format.js # actually means: if the client ask for js -> return file.js
end

js here specifies a mime-type that the controller method would send back as a response;

Default Rails mime-types.

If you try also with format.yaml:

respond_to do |format|
format.js
format.yaml
end

that will mean that your controller will return yml or js depending on what the client-side is asking;

{} in terms of ruby is a block;
If you don't specify any rails will try to render a default file from app/views/[contoller name]/[controller method name].[html/js/...]

# app/controllers/some_controller.rb
def hello
respond_to do |format|
format.js
end
end

will look for /app/views/some/hello.js.erb; // at least in Rails v. 2.3.

If you do specify block:

respond_to do |format|
# that will mean to send a javascript code to client-side;
format.js { render
# raw javascript to be executed on client-side
"alert('Hello Rails');",
# send HTTP response code on header
:status => 404, # page not found
# load /app/views/your-controller/different_action.js.erb
:action => "different_action",
# send json file with @line_item variable as json
:json => @line_item,
:file => filename,
:text => "OK",
# the :location option to set the HTTP Location header
:location => path_to_controller_method_url(argument)
}

end

When assigning attributes, you must pass a hash as an argument

Your params is probably an instance of ActionController::Parameters

If so, you need to permit the attributes you want to use, like so:

def cart_params
params.require(:cart).permit(:attribute1, :attribute2, :attribute3)
end

rails respond_to json format to include two (or more) models and some of their virtual attributes?

Got it!, here's a solution:

        format.json { render json: {user:current_user.as_json(methods:[:full]), assignable:@project}}

What is the proper REST response code for a valid request but an empty data?

TL;DR: Use 404

See This Blog. It explains it very well.

Summary of the blog's comments on 204:

  1. 204 No Content is not terribly useful as a response code for a browser (although according to the HTTP spec browsers do need to understand it as a 'don't change the view' response code).
  2. 204 No Content is however, very useful for ajax web services which may want to indicate success without having to return something. (Especially in cases like DELETE or POSTs that don't require feedback).

The answer, therefore, to your question is use 404 in your case. 204 is a specialized reponse code that you shouldn't often return to a browser in response to a GET.

The other response codes are even less appropriate than 204 and 404:

  1. 200 should be returned with the body of whatever you successfully fetched. Not appropriate when the entity you're fetching doesn't exist.
  2. 202 is used when the server has begun work on an object but the object isn't fully ready yet. Certainly not the case here. You haven't begun, nor will you begin, construction of user 9 in response to a GET request. That breaks all sorts of rules.
  3. 400 is used in response to a poorly formatted HTTP request (for instance malformed http headers, incorrectly ordered segments, etc). This will almost certainly be handled by whatever framework you're using. You shouldn't have to deal with this unless you're writing your own server from scratch. Edit: Newer RFCs now allow for 400 to be used for semantically invalid requests.

Wikipedia's description of the HTTP status codes are particularly helpful.
You can also see the definitions in the HTTP/1.1 RFC2616 document at www.w3.org

Rails render head vs. status

There is no difference really. The Rails doc says this about head:

The head method can be used to send responses with only headers to the
browser. The head method accepts a number or symbol (see reference
table) representing an HTTP status code

head :ok sets render to return just the header with status 200.

It's merely a shorthand for render nothing: true, status: :ok.

Rails 5 will also do head :no_content by default when you don't have a template defined for an action

Rails: Updating Nested attributes - undefined method `to_sym' for nil:NilClass

I've figured it out. I read that a join table like MatchTeams doesn't need an ID. I'm guessing this is true when not doing any nested forms. I redid my migration removing the exclusion of the id column, and now everything works fine. Don't we all love this stupid errors? :)



Related Topics



Leave a reply



Submit