Form within a Form in Rails

I have a user model, and a user has many projects. When a user edits their profile, they can also add projects. A project is a separate form.

But form within a form is not HTML compliant and functionality doesn’t work when I try to add a <%= form_for %> within another <%= form_for %>.

Is there a simple way to handle this? I’d like to build it so that a user can add a project one at a time and submit via ajax, without submitting the entire form.

Rails has a feature called nested attributes that allows nested forms to be created.

The Rails guides has a pretty good overview of how this works. http://guides.rubyonrails.org/form_helpers.html#building-complex-forms

Also have a look at the Rails docs for an overview of how fields_for works. http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for

That should get you started and on the right track. Let us know if you have any questions! :smile:

I saw that, except I was under the impression you would still just be submitting one big form.

What I’m looking for in the UI is the ability to “add” individual projects one at a time. But with nested forms, it looks like you have to fill out all your form data, then submit, then rails separates the forms to their appropriate models.

Right?

Not sure if this screenshot helps but basically I want users to be able to submit mini forms on the page (projects), and then they can submit the main form at the bottom…

Wouldn’t Add Project simply add more inputs to the same form and not be a “form within a form”?
i.e. it doesn’t submit, it modifies.

I’m not certain I fully understand what you’re trying to do.

It sounds like you want 1 form for the users profile and a separate form for their projects on the same page?

Have a look at the following Railscasts and see if they help.

Wouldn’t Add Project simply add more inputs to the same form and not be a “form within a form”?
i.e. it doesn’t submit, it modifies.

Step 1: User clicks ‘add project’ and new form fields appear.
Step 2: User fills out new form fields
Step 3: User clicks ‘add project’ button which either a) saves the project instantly or b) will save the project when the main form is submitted

I’m fine to go with option b) but not sure how I would make it so the project is only submitted IF the user has clicked ‘add project’ (i.e. don’t want project to submit if user hasn’t confirmed it by clicking the ‘add project’ button)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.