Reputation: 944
I am currently building an application that needs remote form, and it came across me that I never really understood how rails respond_to
work.
For example, I have the following code in the view
<%= form_tag ..., :remote => true %>
<%= submit_tag "submit" %>
<% end %>
And I have a javascript partial named _home.js.erb
, suppose the action related is named home
.
I understand that if I have the following code in my controller:
def home
# ...
respond_to do |format|
format.html
format.js { render :partial => 'home' }
end
end
This will execute the javascript in _home.js.erb
when the submit button for the form is pressed. However, what exactly is going on when the submit button is pressed? How exactly does rails know whether to respond_to
html or javascript?
Thank you very much!
Upvotes: 1
Views: 322
Reputation: 492
In the options hash the remote: true
is requesting Rails to respond with javascript.
If you have a web inspector, you check out your network tab, submit the form, and you can see that in the http request headers that the post request is requesting javascript in the accept field. If you did not have the remote tag in the options hash, your form submission would be requesting html.
Additionally, if you do a rake routes in your project directory, you'll see that almost every route ends with the .:format keyword /posts(.:format)
that allows your controller to respond to multiple types of formats a user could potentially define in the specific controller.
Upvotes: 0
Reputation: 7324
The Responder object renders content if the headers indicate that it is of type
else, a magic method is invoked that calls a object.method that is the name of the respond type (e.g. csv
)
This requires that such a method is defined as a handler of the response type. A good discussion of how to create custom responders was answered here.
Upvotes: 1
Reputation: 11342
The submit button posts the form with certain headers/mimes set. respond_to
decided how to act based on the content type, verb and the resource status of the request.
See here for details: ActionController::Responder < Object
Upvotes: 0