Friday, December 2nd, 2005

Real-world Rails RJS templates

Category: Ruby

Ajax is getting even easier for Rails developers. Scott Raymond has talked about his first use of RJS Templates for IconBuffet.

Using RJS, Scott was able to get rid of a bunch of JavaScript and replace it:

This addition allows you to generate Javascript from Ruby, which can be returned by Ajax calls and evaluated in the page. As usual, I use link_to_remote, Rails’ standard way to create an Ajaxified link:

link_to_remote "Add to Cart", :url => { 
  :action => 'add_to_cart', :id => product }

The controller saves the product id and renders the add_to_cart view—but instead of the usual .rhtml or .rxml template, it’s an .rjs template:

page.replace_html 'cartbox', :partial => 'cart'
page.replace_html 'num_items', :partial => 'num_items'
page.send :record, 
   "Element.addClassName('product_#{@params[:id]}', 'incart')"

These three lines accomplish the same thing as the fourteen lines of Javascript above. The first line renders the ‘cart’ partial into the DOM element #cartbox. The second line does the same thing, but for the header. The third line just creates a line of Javascript to add a CSS class to an element.

Update: Scott Raymond just made a plugin out of RJS, so you don’t need to be running edge rails.

Posted by Dion Almaer at 8:18 am

4.2 rating from 18 votes


Comments feed

Thanks for the pointer.

You might want to include the URL of Scott’s post:

Comment by cboone — December 2, 2005

Duh, Sorry, it’s in there now, as well as the update!



Comment by Dion Almaer — December 2, 2005

Actually, Cody Fauser made that RJS plugin, not me.

Comment by scott Raymond — December 5, 2005

[…] RJS Templates – This is another HUGE feature. I don’t know anyone that wants to sit down and conjur up Javascript all day long. Well, now we can write Javascript using Ruby. How bad-a$$ is that? Explanations here, here, and here. […]

Pingback by Rails 1.1 is out — March 28, 2006

i am glad to breaking the silence to announce, that
This is such a great resource list of WordPress Templates. I have posted about your site several times on my blog.

No need for anyone else to keep adding to their list when you have it all.

Comment by Smith — May 2, 2006

really a great entry.

Comment by Smith — May 2, 2006

Beauty Tips, Hair Styles, Fashion, models, clothes, beauty, chic, catwalk, UK, collection and More at

Comment by John — May 5, 2006

rjs – real good thing, very simple!

Comment by sarman — July 18, 2006

Leave a comment

You must be logged in to post a comment.