Ajax-based Dependent Dropdown in Rails

drupal_developer's picture

Today I am gonna explain you about how I did ajax-based dependent dropdown in one of my rails application.
According to my project requirement there were projects and each project contains many applications.
I actually needed a search form there which search all resources of that project - application.
But here lets just go with how to populate second dropdown upon change of first.
First we need to create a controller in my case I've created projects_controller.rb .
Which contains two actions one index and another get_applications to populate applications.

class ProjectsController < ApplicationController
def index
@projects = Project.find(:all)
end
def get_applications
if params[:project_id]
@apps = App.find(:all, :conditions => {:project_id => params[:project_id]})
else
@apps = App.find(:all, :conditions => {:project_id => 1})
end
end
end

then lets create index.html.erb file in views. Here I am not using any layouts just for testing purpose.

<%= javascript_include_tag :defaults %>
<% form_tag({}, {:name => "show_list", :id => "show_list"}) do -%>
Projects

<select name="project_id" id="project_id">
<option value="0">Select Project</option>
<% @projects.each do |project| %>
<option value="<%= project.id %>"&glt;<%= project.name %></option>
<% end %>
</select>

Applications
<div id="application_id_container">
<select name="application_id" disabled="disabled">
<option value="">No Application</option>
</select>
</div>

<%= observe_field("project_id",
:frequency => 1,
:update => "application_id_container",
:url => { :action => :get_applications},
:with => "'project_id='+value") %>
<% end %>

after this we need to create a get_applications.js.erb file to update div with second dropdown.


<select name="application_id" >
<% for application in @apps %>
<option value="<%= application.id %>"><%= application.name %></option>
<% end %>
</select>

keep the above two files in views/projects.

 

Free Web Hosting
v>