Ruby On Rails - HOWTO Show/Hide Div

This is a simple article to demonstrate how easy, simple and effective it can be utilising the web2.0 functionality made simple in Ruby On Rails.

There are 4 steps to building a simple show/hide div.

1.

Include the Javascript libraries. This is best placed in your layout, so in a default project using the standard layout, open app/view/layouts/standard.rhtml. After the head tag, put the following:

2.

Build your form pieces. Firstly we need to define a form and an ajax action for that form. In this example I will be using a check box.
The following form belongs in a view and should look like this:

"processapplication" do-%> By checking this box, I agree to the terms and conditions. n => :selected, :update => :submitdiv, :url => { :action => :accepted_terms }) %>

So we have defined a observefield which will fire a AJAX request to ‘:acceptedterms’, which is an Action. If you change the form or objects, you will need to update the name of the field to observe (first field).

We have also specified the submit_div as the location for our returned information from the ajax request, which as you can see is blank by default. We plan to render a submit button so then can continue with the form once they select the check box.

3.

Now we open our controller and write the action ‘accepted_terms’ to make a decision if the check box is selected.

def acceptedterms if params["1"] render :partial => "submitapplicationbutton" else rendertext "You cannot continue without agreeing to the Terms and Conditions." end end

So as this action executes it renders to our submit_div.

4.

In our controller we render a partial, so in your view directory, create a partial called: ‘submitapplication_button.rhtml’

This allows the user to actually submit the form specified in step 2.

There are other ways of using the ajax requests, you can add params by modifing the url section:

:url => { :action => :accepted_terms, :id => 4 }) %>

And there are much more possibilities, as I get more time to document them I will add to this article.