I’m trying to build a multi model form – but one of the issues, is I need to link the models within the form.
For example, lets say the form I have has the following models: Users, Profiles
When creating a new user, I’d like to create a new profile simultaneously, and then link the two. The issue is, if neither have been created yet, they don’t have ID’s yet – so how can I assign linking values?
Thanks!
-Elliot
I noticed, some people are favoriting this – to view more about linking the two models, check out my second question which has the answer: Linking two models in a multi-model form
One way to achieve the desired result is that you can craft a form that takes advantage of nested attributes support in Rails:
You will also need to add the following to your User class:
You can read more about Active Record Nested Attributes here.
You can read more about the ActionView Form Helpers here (search down the page for “Nested Attributes Examples”).
If you use this approach, along with good validations on both models, you won’t have to worry about tracking the database IDs, because both will be created at the same time by ActiveRecord (but not until both model objects are valid).