Linking two models in a multi-model form

Posted by Elliot on Stack Overflow See other posts from Stack Overflow or by Elliot
Published on 2011-01-02T23:50:11Z Indexed on 2011/01/02 23:53 UTC
Read the original article Hit count: 237

Hey Guys,

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!

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby