I don't understand how :remote => true works in rails. I know that when I write it an ajax request is sent and the .js response is made. But how does this work? I mean, where does the action go, etc.?
Rails UJS (Unobtrusive JavaScript) is the JavaScript library that helps Rails do its magic when we use options like remote: true for many of the html helpers. In this article I'll try to explain the main concept of how this works to make it transparent for the user.
Rails uses a technique called "Unobtrusive JavaScript" to handle attaching JavaScript to the DOM. This is generally considered to be a best-practice within the frontend community, but you may occasionally read tutorials that demonstrate other ways.
The Rails documentation for remote: true is great at explaining how to add the helper to your views. It does not, however, fully explain how remote: true works in tandem with a controller and a Javascript file to generate and manage JSON responses to the ajax call.
It does not, however, fully explain how remote: true works in tandem with a controller and a Javascript file to generate and manage JSON responses to the ajax call. AJAX involves a clientside (browser) request to your server that generates a response back to the client that must be handled.
AJAX involves a clientside (browser) request to your server that generates a response back to the client that must be handled. Below is a short tutorial on how to craft the full circuit of requesting and responding via remote: true ajax calls in Rails. You can add the Rails helper remote: true to any other Rails helper that generates a web request.
If you want to submit a form using AJAX you can do this without having to write an AJAX request. Rails can handle it for you. How? Use the remote: true option with form_for. Now when you click “Create” Rails will send an AJAX request for you & the page won’t reload.
Let me explain the whole flow of AJAX-Rails and remote=> true.
First, when you add remote => true to the form it will submit or call the action which you have defined in the form.
Here is an example:
<%= form_tag({:controller => 'my', :action => 'my_data'},:id => 'filter_form', :remote => true) do %> #code here <%= submit_tag 'save', :name => 'commit'%> <%end%> Now, the above code will go to my_data action in my controller.
Here you can define the response type with:
def my_data #actions on data here respond_to do |format| format.js end end Now you have to make a ".js"" file with the same name as the action:
my_data.js.erb This ".js" file will handle the form. You could write and update document elements through jQuery and JavaScript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With