Sara Me,
I spent a good amount of time studying this example this morning and
have compiled a listing of what I 'think'? your code settled as, in
the hopes of replicating your brilliant technique. I enclose my
writeup at the end of this entry.
My main confusion is "How did you get the cities dropdown to
populate"? I see a get_cities.rhtml but can't imagine how it was
called UNDER the observe_field? I don't see a partial call. From what
I can see it MAGICALLY appears.
I see how the observe_field fires the controller action, but am left
in the dust as to how the get_cities.rhtml is made to appear.
I am grateful for any explanations.
Kathleen
Here's my best synopsis (below)
I am trying to create dynamic dropdowns in a form, such that when a
user
clicks an item in select list #1 (States), the options in select list
#2
(Cities) will update to reflect only cities that are in the selected
state.
I know this can be done with Javascript, but I came across a little
snippet online (see <a href="http://nealenssle.com/blog/2007/04/12/how-
to-dynamically-update-form-..."
target="_blank">this blog by Neal Enssle</a>) that does it all in
Rails
and that would be amazing if I could get it to work because I'm really
not big on JS.
I can't get this code to work. When I select a state in the first
dropdown, the 2nd dropdown does not populate.
Here is the code in controllers/dyn_drops_controller.rb:
def get_cities(find_state)
@cities = City.find_all_by_states_id(params['states_id'])
end
Here is the code in views/dyn_drops/index.html.erb:
<form>
<select id="states" name="states">
<option value="0"></option>
<option value="1">New York</option>
<option value="2">California</option>
<option value="3">British Columbia</option>
<option value="4">Ontario</option>
</select>
<%= observe_field "states", :update => "cities", :with =>
"states_id" :url => { :controller => "dyn_drops", :action =>
"get_cities" } %>
<br />
<select id="cities" name="cities">
<option value="0"></option>
<option value=1">test option</option>
</select>
</form>
Here is the code in views/dyn_drops/get_cities.rhtml:
<% for city in @cities -%>
<option value="<%= city.id %>"><%= city.name %></option>
<% end -%>
I also have a model named city.rb. One MySQL db table is named
'states'
and contains fields 'id' and 'name'. The other db table is named
'cities' and contains fields for 'id', 'name', and 'state_id'.