Search code examples
ruby-on-railsformtastic

Cascading dropdown using MySQL database, Formtastic and Active Admin


I have managed to create a drop-down that is filled from the service model. The service model is managed from a MySQL table. I used this code:

f.input :service, :as => :select #<-- :as not really needed, I know...

I would like to have another select box below the service select that is filled with teams from the team model (teams table in MySQL database) based on what the user selected from the service select.

For example if Service 1 was selected from the service select then the team select would be filled with the teams (Team 1, Team 2) that have the foreign key of service_id = 1 in the teams table in the database. If anyone could help with how to insert the correct associations and Formtastic code to achieve this I would greatly appreciate it.


Solution

  • If you want the contents of one select to change (reduce the number of options) based on the selection made in another select box, this is mostly a client-side programming issue — Formtastic can't modify the DOM once sent to the browser.

    You need one piece of JS to watch for changes in the Service select, and another to modify the Team select in some way based on that selection. For this, you have a heap of options here, but it's really not a Formtastic issue, other than perhaps how to render the correct markup for your JS to work.

    In the past, I've done all of these at different times:

    1. rendering a separate Team select box for each possible Service selection, then showing/hiding the correct one in the DOM as needed with JS

    2. rendering a data attribute on each option in the Team select noting which Service it support so that the JS can remove or disable options based on the Service selected

    I prefer #2, but #1 is probably easier within Formtastic.