Dependent Ajax Dropdowns
January 7, 2008 Ajax, Rails, jQuery No Commentsi needed to connect three select dropdowns in the project i am working. i am using jquery, so i could not use the observe_field helper that seems to be the dafault rails way to do it, also i will use these three combo boxes in another forms inside the project, so the solutions needed to be reusable.
the final solution isn’t exactly what i wanted, but seems pretty usable (and reusable) for now.
i discovered a method called render_component that allows me to render an action from another controller inside a view. with this in mind i made a LocationController with three methods: countries, states and cities. the view for each method is similar to this:
<code>
<% unless @states.empty? %>
<%= options_from_collection_for_select @states, ‘id’,'name’,@default_state %>
<% else %>
<option value=”">Select a country first</option>
<% end %>
</code>
so the jquery was:
<code>
$(”#country”).change(function(){ $(”#state”).load(’/locations/states’,{id: $(’#country’).val()}) });
</code>
for making it easily reusable i just made a helper method so i needn’t to rewrite any code.
next step now is to make it restful, and that isn’t hard. I just don’t know what kind of format i should use to recover just the options, since the index method is meant to bring a list of countries.
Blogged with Flock