This post originated from an RSS feed registered with Ruby Buzz
by Robby Russell.
Original Post: Adding AJAX to your existing RAILS app, part 2
Feed Title: Robby on Rails
Feed URL: http://www.contegix.com/rss/feed.xml
Feed Description: My reflections on programming with Ruby, Rails, PostgreSQL... and learning how to run a business...
With the release of Rails 0.11.1, we were given the, “Yellow Fade Technique” that was shown in Basecamp. This has shown up in Typo and taskTHIS (and probably many other places..). So, how can you add this to your existing Rails application in just a few steps?
In our example, we are going to accomplish two things. One, we are going to avoid the seperate new page that you get with the generated scaffolding, so at the bottom of our standard scaffolding table for list, we will display a form that will populate the database (1) and then display the new data in the table and while we’re at it, use the Yellow Fade Technique (2). Okay, so this is more than just 2 items to tackle… but I had two goals and this is how I reached those goals.
Step 1: Upgrade to at least 0.11.1.
Step 2: Add this to the <head> of your HTML.
<%= define_javascript_functions %>
Step 3: Open up your list.rhtml file (in my case this is for a list of divisions). Let’s add the following below the Create New link that comes with the stock generate script.
Step 4: While in list.rhtml, modify your table to look something like this:
<table id="divisions-list" class="divisions-list">
<tr>
<% for column in Division.content_columns %>
<th><%= column.human_name %></th>
<% end %>
</tr>
<% for division in @divisions %>
<%= render_partial( 'division', division ) if division.active? %>
<% end %>
</table>
Step 5: Create _division.rhtml in the same folder as list.rhtml. This is what gets called in render_partial. Populate it with the following:
Step 6: Now, to make it all work. Edit your controller (in my example, division_controller.rb). Create a new method (I named mine create_ajax).
def create_ajax
@division = Division.new(@params['division'])
if @division.save
render_partial 'division', @division
end
end
Step 7: Test it out. It obviously needs some validation, cleanup of the javascript into a seperate file (so that we only include what we need), but this is all it takes to add a quicker method of adding data to a table using AJAX and it looks nice with the Yellow Fade Technique.
Thanks to Typo and taskTHIS for providing nice working examples for me to work off of.