javascriptjqueryruby-on-railsrjs

Alternatives to RJS for Rails


I have heard that the idea in RJS of passing to the client js code instead of json or html disturbs many people and so they avoid RJS. Given that what exactly would be the idiomatic way to do ajax with jquery in the Rails framework with no RJS? Is there maybe a tutorial link someone could point me to?


Solution

  • There are two main ways to achieve AJAX via rails:

    The first is using js.erb files, :remote => true option in links and forms and

    respond_to do |format|
      format.js
    end
    

    in the controller. There is a very good explanation of how to implement it here.

    The other way is to write plain Javascript (you could certainly use the help of JQuery) to send AJAX requests to the server and handle them in the client side. With this approach the Javascript is written in seperate JS files in the assets folder of your app.

    From my experience, for the long term it is better using the second way for three reasons:

    1. It gives you a complete separation of client side and server side code. One programmer can deal solely with one aspect of the code and that's a big advantage.

    2. It is a lot easier to test seperate JS files than js.erb files.

    3. It makes it easier to reuse javascript code, and package it for minification and such when you go to production.