Hi all,
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 this blog by Neal Enssle) 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
@cities = City.find_by_state(:all)
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 =>
“city_id”, :url => { :controller => “test”, :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’.
I am a newbie to RoR so I’m sure the problem here is something really
dumb I’m missing. I know there’s a lot of info above, so any help would
be greatly appreciated!!