Sorry if this is a duplicate, I can't find the answer anywhere!
In short, I need to dynamically add an item to a drop down menu in a form without losing any edits.
More specifically, I'm adding a recipe in a rails form. Each ingredient has a field for quantity, a drop down containing all the existing ingredients and then a field for a description of the ingredient. My Rails form successfully adds the recipe, sets up the association between the recipe and the recipe_ingredients
table (a go-between table that lists the recipe_id, the ingredient_id, amount and so on) and successfully pulls the name of the ingredient from the ingredients
table. All good there. So, recipe.recipe_ingredients
will list all the ingredients in the recipe and recipe.ingredient.first.name
will say "Pasta" or whatever. Everything is working fine.
BUT, if the ingredient name doesn't already exist in the ingredients
table I can't figure out the best way to add that ingredient to the drop down without scrapping the whole recipe and going to another page to add the ingredient to the ingredients
table and going back to the recipe page to add the recipe again.
I'm not sure the best way to do this. I was thinking of having a form in the sidebar to add a new ingredient to the ingredients table (ingredients have a name and a category - dairy, produce, etc) so it's not enough to just have a blank field in the original form for the new name. But I have two problems with that. I'm not sure what to add to the ingredients
form on the recipe page to have that form interact with ingredients controller and not the recipes controller. Something in the submit button telling it which controller to use? And I don't know how to then dynamically update the drop down menus in the recipe form to update the menus with the new item. Especially without resetting the state of the previous drop downs - which might be just saying update the "last" drop down of its class?
I'd be happy to supply any code to clarify, just don't want to overwhelm with unnecessary details.