# Cascading select box

**URL:** <https://www.ruby-forum.com/t/cascading-select-box/105902>\
**Category:** Rails\
**Created:** [June 4, 2007, 2:24pm UTC](https://www.ruby-forum.com/t/cascading-select-box/105902 "2007-06-04T14:24:30Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![dhaval](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/85e7bf/32.png) [@dhaval](https://www.ruby-forum.com/u/dhaval)\
**Post date:** [June 4, 2007, 2:24pm UTC](https://www.ruby-forum.com/t/cascading-select-box/105902/1 "2007-06-04T14:24:30Z")

</div>

hey people i am trying to create dynamic drowns with three select  
boxes and using one model …if i change first drop down then the  
second gets updated but the third one doesnt get updated…could u  
please tell me wat is the problem

here is the controller code

class AdminController \< ApplicationController  
def state\_update  
return unless request.xhr?  
cities = State.find\_by\_sql(“select distinct city\_name from states  
where state\_id=#{params[:state\_id]}”)  
render :update do |page|  
page \<\< update\_select\_box( “city\_id”,  
cities,  
{:text =\> :city\_name,  
:clear =\> [‘area\_id’]})  
end  
end  
def city\_update  
return unless request.xhr?  
areas = State.find( :all, :conditions =\> [“city\_id=?”,  
params[:ecosite\_index]])  
flash[:notice]="#{params[:ecosite\_index]}"  
render :update do |page|  
page \<\< update\_select\_box( “area\_id”,  
areas,  
{:text =\> :area\_name} )  
end  
end

def index  
@states=State.find\_by\_sql(“select distinct name,state\_id from  
states”)

end  
end

here is the view

\<%= javascript\_include\_tag :defaults %\>  
\<%= start\_form\_tag %\>  
\<% options = [[“Select State”, " "]] + @states.collect { |c|  
[c.name,c.state\_id] } %\>  
\<%= select(“state”, “id”, options) %\>  
\<%= select( “city”, “id”, [] ) %\>  
\<%= select( “area”, “id”, [] ) %\>  
\<%= submit\_tag %\>  
\<%= end\_form\_tag %\>

\<%= observe\_field “state\_id”,  
{:url =\> {:action =\> ‘state\_update’},  
:with =\> “state\_id”} %\>

\<%= observe\_field “city\_id”,  
{:url =\> {:action =\> ‘city\_update’},  
:with =\> “ecosite\_index”} %\>

this is the helper code

def update\_select\_box( target\_dom\_id, collection, options={} )

# Set the default options

options[:text] ||= ‘name’  
options[:value] ||= ‘id’  
options[:include\_blank] ||= true  
options[:clear] ||= []  
pre = options[:include\_blank] ? [['select ','select ']] : []

out = “update\_select\_options( $(’” \<\< target\_dom\_id.to\_s \<\< “’),”  
out \<\< “#{(pre + collection.collect{ |c| [c.send(options[:text]),  
c.send(options[:value])]}).to\_json}” \<\< “,”  
out \<\< “#{options[:clear].to\_json} )”  
end
