It has been a few weeks now since I started programming in Ruby and Rails. I really have it enjoyed it and I’m very impressed with Rails. However, I recently took some time to learn about the Ajax support in Rails and came away somewhat confused.
You see, Rails is an MVC (mode-view-controller) framework. However, the Ajax support in rails seems to encourage a developer to include view logic in their controller. Since one of the main benefits of Rails is the MVC framework, I was a bit confused by this.
Now, to be fair, my opinions here were formed after reading one article, Ajax on Rails by Curt Hibbs, and I’m still a Rails newbie.
Let me provide an example of what I found concerning. There form_remote_tag contains a paramter where you specify the ID of a DOM element that will be updated the action contain within the controller code.
For example,
form_remote_tag(:update => “my_list”, :url => { :action => :add_item }, :position => “top”)
This code snippet inidcates that add_item action is called in the controller when the form is submitted.
The controller code looks like this,
class ListdemoController < ApplicationController
def add_item
render_text "<li>" params[:newitem] "</li>"
end
end
As you can see, HTML is generated from the controller. This means if you change the code in your view, you may need to go back and change the HTML generated by the controller so that is fits with the changes you made to your view. This is excatly the type of thing Rails avoids in so many other instances, and exactly why I’m so excited about Rails. What’s up with that!
I began to poke around the Ajax for Rails API documentation and found some reference to registering a client side javascript function that would be called. However, I wasn’t able to make this all work. I wasn’t able to find any good examples online and hope the new Rails book I ordered (Agile Web Development with Rails) will help.
In any event, I’m still very excited about Rails and hope this means there is still some opportunity for me to add to the community once I feel like I’ve overcome the learning curve.
Generally, the preferred way to do it is to do a "render :partial => '...'" rather than inlining HTML into the controller. But, if you're not a purist and the case is as simple as Curt's example, it might be worth sacrificing purity for simplicity/clarity.
Posted by: scott raymond | August 29, 2005 at 01:27 PM
Thanks Raymond. I'll try this out. For the app I'm building, I want more purity. I'm sending down a bunch of XML that will be used in different ways.
Posted by: Alex Castro | August 29, 2005 at 02:09 PM
Yeah, the use of render_text is just a quick hack. . .
the proper thing to do is to use partials. Then have the control use the partial view (the same partial view that is used to construct the page in the first place).
found your site from Jeff Barr's article about amaozn employees :)
Posted by: Jesse Andrews | September 07, 2005 at 11:48 AM