4

I've recently started learning Ruby on Rails, based on RoR3 beta/RC. I had earlier been developing applications using other frameworks (like Django), where the JavaScript had been written completely on my own.

When developing application using RoR, I get confused by the two possible ways of implementing JavaScript: the "pure" one (writing JavaScript and putting it in the <script> tag) and writing RJS files.

Which of the approach should rather be used and when? If RJS, how do I implement particular actions like onChange?

mhaligowski
  • 2,182
  • 20
  • 26

2 Answers2

6

In rails you should use both approaches for different tasks. So do I. When I would like to execute ajax request, I use RJS because it simplifies the request and allows to write more powerful and flexible respond within .rjs file with a much less code. For example it is possible to use partials in it and to get access to ruby variables. When I would like to make a page more dynamic, I use plain javascript including it with javascript_include_tag.

UPD. This approach works in rails 3 the same way. It's possible to use it with JQuery and HAML. UJS in Rails 3 even simplifies it. The only thing you should do is to use jquery-ujs if you prefer Jquery over Prototype and proper file naming like create.js.haml. For example it possible to use server-side validation in AJAX requests with this approach.

Community
  • 1
  • 1
Voldy
  • 12,829
  • 8
  • 51
  • 67
4

In rails 3 the right way to do it is pure JS. RJS is too strict and you have to use Prototype or hack in some way to use it with jQuery. Rails 3 also promotes unobtrusive javascript. On AJAX requests you should return pure Javascript embed with ERB instead of using RJS.

Unfortunately since this change requires a lot of rework for older projects that used RJS some people will leave it be.

The RJS is actually depreciated in rails 3, you need a plugin to even work with it, so if you're starting now and you're lucky enough to start on rails 3 already, go the rails 3 way.

Here is a good example of the new UJS way: http://railscasts.com/episodes/205-unobtrusive-javascript

Good luck

Draiken
  • 3,805
  • 2
  • 30
  • 48
  • This is the best answer. RJS should not be used anymore and the closest alternative is to render a `.js.erb` file. If the client makes an AJAX request (type 'script' if using jQuery) then the server action would, for example, `render partial: '/whatever/partial'`. The partial file would be `PROJECT_ROOT/app/views/whatever/_partial.js.erb`. – antinome Jul 30 '14 at 18:27