Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of .js.erb for Ajax in Rails 3 (jquery .js vs .js.erb)

I have two alternatives to implement ajax in a Rails 3 application.

1- Bind the event on the submit using jquery within the file viewaction.js or viewaction.js.coffee and manage the returned json to modify things in the DOM.

2- Use remote=>true tag in Rails and code a file named viewaction.js.erb to make the modifications in the DOM and use class variables loaded in the controller.

  • What is the recommended approach in Rails 3?
  • What is the Rails way to do it?
  • What is the best practice?
  • Specific scenarios when one of the alternatives is best than the other?
  • What is the recommendation for big projects?

Thanks

like image 989
Tony Avatar asked May 29 '12 19:05

Tony


People also ask

What is JS Erb in rails?

.js.erb files are for controller actions, such as create, when you want javascript to be executed when the action completes. For example, when you want to submit a form via ajax and want display an alert when everything is done, you would put the $('#business_submit'). click(...) in your application.

Can you use JavaScript with ruby on Rails?

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.


1 Answers

Prior to Rails 3, adding :remote => true would have generated a bunch of inline JavaScript inside the form tag, but with Rails 3 UJS, the only change is the addition of an HTML 5 custom attribute data-remote=true. for example:

<%= form_for(@post, :remote => true) do |f| %>  

will generate

<form accept-charset="UTF-8" action="/posts" class="new_post" data-remote="true" id="new_post" method="post">  

for now, this is the rails3 approach. the js function that generates it is under rails.js file. If you open the rails.js file, you will notice several remote handler definitions. The first one handles the case of remote form submission, the second one handles remote links and input fields, the third handles not-remote links that should behave likes form.

from looking deeper into the code i found that this file actually perform a jQuery ajax call:

ajax: function(options) {
      return $.ajax(options);
    },

so there is no difference between using :remote => true and a regular jQuery ajax call, rails acts like a wrapper to call the same methods.

more info here, here and here.

like image 115
Sagiv Ofek Avatar answered Sep 17 '22 17:09

Sagiv Ofek