Cascading selects with AJAX in Rails
This image will clarify the problem without any words:
The first thing which I should pay attention to in my solution is a jQuery library:
This peace of code extends jQuery with a dynamicSelectable function which you can call on select which should be listened to change and populate the dependent select. The listened select should has data attributes: selectable-url and selectable-target. Their names explain what they are for:
selectable-url - is an url pattern with the model id. For example:
/dynamic_select/:country_id/states. In this case the pattern should be populated with the chosen country id (assuming that we add listener to country’s select) and request will go to this url to get JSON data for populating related select.
selectable-target - is a css selector of select which should be populated with given JSON data from the server.
I call dynamicSelectable function for every select on the page which has both data attributes selectable-url and selectable-target simultaneously:
To make our application workable we should have a controller which will be responsible for the route
/dynamic_select/:country_id/states. Firstly have a look at how I generate route:
And this is how my controller looks:
And this is a template of index action:
Returned JSON data from server should not include root elements:
And the last thing which I should focus on is a form:
If you have any proposals concerning this solution or if you have spotted any typo, bug, inconsistency or lacks feel free to contact with me.