There is a model A that has_many
B and a form where one can create a new A and
add/remove Bs. I.e. there is a link Add new B that runs some Javascript to insert another partial where one fills in values for B. All works fine.
The problem
Specifying a B is done through selecting the values using a couple of select boxes. The problem is that depending on a value selected in one, the collections used in the other selects should be scoped to only show relevant options. It's the classic case with dynamic select boxes (think country - state select boxes), only with more select boxes and I'd like all the select boxes to appear initially, so the user can start from anywhere (select state first and country select box narrows down its collection to the ones that can be chosen for that state).
Current approach
The Bs are rendered in a table, one B per row and I was thinking that I could use AJAX to replace the table row (content) after fetching the new collections from the server. This obviously needs a couple of things in place.
tr
tag must have a unique id attribute, so replace_html can be used.- need to have a trigger on change for each select box
- need to pass all select boxes' values (for that row) to the server
I'm stuck here, because of the following:
- adding a B needs to have something unique to identify the
tr
tag as well as all the selects on that row. I can useTime.now.to_i
but that won't work for the Javascript run by the link to add a new B because that will hardcode the value and all use the same. - not sure if I should go with
observe_field
or a remote call in the select form field helper. - how to pick up the values of all selects in one row and pass that remotely to the server when triggered?
The project I'm working on is Rails 1.2.3 and uses Prototype. Please feel free to post "newer" solutions too, because I'm curious to see different solutions.
Any help on this is highly appreciated. Thanks in advance!
This doesn't answer your entire question but it might get you started. I handle it like this... this is for playlist entry, where the user can add new forms in a div
#playlist-entry
, and each form is.new_song_form
with a hidden field.form_num
(which I use in thecreate.js.erb
file to tell it which form to hide/warn of validation errors, which isn't really relevant for you I guess).This form is a little different because there's no one "major" form to submit, it's a bunch of forms all on one page, but this basic idea might help you. It's not perfect programming - for example I should be passing
form_counter
as an argument to the function... but it works perfectly.