15 December 2007 ~ Comments Off

Ajax and Ruby on Rails

Submit your form via Ajax and save the results to a database. To do so just follow the steps below. First we need to open the form tag (form_remote_tag), then we will send the form to a url, a position and what id to update!

[ruby]<%=form_remote_tag(:update => “my_list”, :url => { :action => :addtodo, :id => @list }, :position => “top” )%>[/ruby]

This will make the call to update and send the data, at this point be sure to include (prototype) JavaScript into your layout by calling;

[ruby]<%= javascript_include_tag "prototype" %>[/ruby]

Once that’s done lets build the rest of the form;

[ruby]<%=form_remote_tag(:update => “my_list”, :url => { :action => :addtodo, :id => @list }, :position => “top” )%>

Add an item:<%=text_field 'todo', 'todo' %>
<%=submit_tag "Add", :class => “submit” %>

<%=end_form_tag%>[/ruby]

Now, we can start with the controller! The great thing about rails is we only need to make a small change to a normal post. Just add (render_text), in this case I am updating a list. Below is the controller I am using for this example;

[ruby]def addtodo
List.find(params[:id])

@todo = Todo.new(params[:todo])

if @todo.save
render_text “

  • ” + @todo.todo + “

  • else
    flash[:notice] = ‘Sorry, we cant add the item.’
    end
    end[/ruby]

    Adding Ajax to your app is very easy as you can see, just a few lines and your done!

    Comments are closed.