Linking two models in multi-model form

I have a nested multimode form right now using users and profiles.

The user has a has_one profile, and the profile belongs to _ users.

When the form is submitted, a new user is created and a new profile is created, but they are not connected (this is the first obvious problem). The user model has the profile_id line, and the profile model has the user_id line.

Here is the code for the form:

<%= form_for(@user, :url => teams_path) do |f| %> <p><%= f.label :email %><br /> <%= f.text_field :email %></p> <p><%= f.label :password %><br /> <%= f.password_field :password %></p> <p><%= f.label :password_confirmation %><br /> <%= f.password_field :password_confirmation %></p> <%= f.hidden_field :role_id, :value => @role.id %></p> <%= f.hidden_field :company_id, :value => current_user.company_id %></p> <%= fields_for @user.profile do |profile_fields| %> <div class="field"> <%= profile_fields.label :first_name %><br /> <%= profile_fields.text_field :first_name %> </div> <div class="field"> <%= profile_fields.label :last_name %><br /> <%= profile_fields.text_field :last_name %> </div> <% end %> <p><%= f.submit "Sign up" %></p> <% end %> 

The second problem: even if the username and password are successfully created using the form for the user model, hidden fields (role_id and company_id), which are also links to other models, are not created (although they are part of the model) - the values ​​are successfully displayed in HTML for these fields.

Any help would be great!

As requested, the controller code:

  def new @user = User.new @user.profile = Profile.new @role = Role.find_by_name("Regular") respond_to do |format| format.html # index.html.erb format.xml { render :xml => @teams } end end def create @user = User.new(params[:user]) @profile = Profile.new(params[:profile]) respond_to do |format| if @profile.save && @user.save format.html { redirect_to (teams_path) } format.xml { render :xml => @profile, :status => :created, :location => @profile } else format.html { render :action => "new" } format.xml { render :xml => @profile.errors, :status => :unprocessable_entity } end end end 
+1
source share
1 answer

To answer question number one, change the following:

 @profile = Profile.new(params[:profile]) 

to

 @profile = @user.profile.build(params[:profile]) #In the case of a has_many relationship 

or

 @profile = @user.build_profile(params[:profile]) #In the case of a has_one relationship 

The build command creates a new profile with the correct user_id setting.

In the second question, can you remove the request for the role and company during the new action and instead assign them during the create action? This eliminates the need to pass hidden parameters.

+1
source

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


All Articles