Ruby on Rails is a powerful web application framework that provides numerous tools for creating web applications fast! It is a full-stack framework for developing database-backed web applications according to the Model-View-Control pattern. Rails also provides Ajax support in the view layer, a request and response controller, and a domain model wrapping the database. Ajax is a creative technique used to make web sites more interactive and responsive to user input. RJS templates are an exciting and powerful new type of template added to Rails 1.1. This article will introduce RJS templates and show how they allow you to easily add Ajax functionality to your web application.
Rails RJS Templates
You can create a simple Rails application and add RJS support to it. To begin, you need to create a rails app 'rsjtest' by issuing the command 'rails rjstest':
This creates an 'rjstest' directory containing your initial web application:
Creating the Web Page You Will Use to Test the RSJ Template
Within the rails application, the models, views, and controllers of the application live in the 'app' directory. Your intention is to create a simple web page that you can test out a sample RJS template. So, begin by creating the page that will you will use to test the RJS Template functionality. Create a file 'index.rhtml' in the 'app/views/rjs' directory. This will be the default page Rails will serve up to the browser when a URL of 'http://localhost:3000/rjs/' is requested from your web browser. Edit the 'index.rhtml' file and add the following:
Creating the Controller and View
Generate a Controller and View for your test. This controller will be the one defining the action defined in your 'link_to_remote' call specified in the RHTML file. You will be using a controller names 'rjs'. Issue the commands below to create the Controller and View:
You should now have an 'rjs_controller.rb' file in the 'app/controllers' directory and a 'views/rjs' directory. Edit the 'rjs_controller.rb' file and add an empty 'hello' method:
class RjsController < ApplicationController def hello end end
This method is empty because you are not passing anything on to the view, but are allowing your RJS Template to do its magic.
Creating the RSJ Template
To create your RJS template, you need to create a file named 'hello.rjs' in the 'appsviewsrjs' directory. Edit the file to look like the following:
page.alert "Hello from RJS!"