I have a nested multimodel form right now, using Users and Profiles.
Users has_one profile, and Profile belongs_to Users.
When the form is submitted, a new user is created, and a new profile is created, but they are not linked (this is the first obvious issue). The user’s model has a profile_id row, and the profile’s model has a user_id row.
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 %>
A second issue, is even though the username, and password are successfully created through the form for the user model, the hidden fields (role_id & company_id – which are also links to other models) are not created (even though they are part of the model) – the values are successfully shown in the HTML for those fields however.
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
To answer question number one, change the following:
to
or
The build command builds a new profile with the user_id properly set.
For the second question, can you delete the query for Role and Company during the new action and instead assign those during the create action? This would remove the necessity of passing hidden parameters.