Question

A "user" has_many "foods" through "favorite_foods".

How can I make a form that creates multiple new rows in "favorite_foods"?

I'd imagine a form with checkboxes for each food, but this is different than usual Rails forms since I'm inserting multiple rows into a table, instead of just one row (e.g. when saving a new user).

users
email:string first_name:string last_name:string

foods
name:string 

favorite_foods
user:references food:references
Was it helpful?

Solution

Forms don't create rows, controllers do, via calls to models. If there are few enough foods to enable you to have a checkbox for each one, then your controller can just go through the params and create a favorite_food entry for each one checked.

If you have more food choices that you can reasonable represent via a checkbox, then you can pass an array of choices via the form, as described in http://guides.rubyonrails.org/form_helpers.html#basic-structures

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top