Creating a nested model

I am trying to create a multi-model form - but one of the problems is that I need to link the models in the form.

For example, let's say the form I have has the following models: Users, Profiles

When creating a new user, I would like to create a new profile at the same time, and then link the two. The problem is that if they are not already created, they do not have an identifier yet - so how can I assign binding values?

Thanks!

-Elliot

I noticed that some people prefer this - to learn more about the link to two models, check out my second question, to which there is an answer: Linking two models in multi-model form

+4
source share
1 answer

One way to achieve the desired result is that you can create a form that uses support for nested attributes in Rails:

<%= form_for(@user) do |f| %> <%= f.label :my_user_attribute %> <%= f.text_field :my_user_attribute %> <%= f.fields_for :profile do |fp| %> <p> <%= fp.label :my_profile_attribute %> <%= fp.text_field :my_profile_attribute %> </p> <% end %> <%= f.submit %> <% end %> 

You also need to add the following to your User class:

 accepts_nested_attributes_for :profile 

You can learn more about active nested entry attributes here . You can read more about the helpers of the ActionView form here (search on the pages "Examples of nested attributes").

If you use this approach along with good validation on both models, you don’t have to worry about tracking database identifiers, because both of them will be created using ActiveRecord at the same time (but not until both model objects are valid).

+5
source

Source: https://habr.com/ru/post/1333999/


All Articles