Topic: Handling a form which belongs to a different model

Hello,

I've got two models: user and profile, and I would like to use the same form in order to input data into them.

I work within the user view and controller. I have a working form for the user colums. However, when it comes to the profile model, how can I access it from the user view?

user.rb:

class User < ActiveRecord::Base
    has_one :profile                
#....#
end

profile.rb:

class Profile < ActiveRecord::Base
  # attr_accessible :title, :body
    belongs_to :user
end

users/new.html.erb:

<%= form_for @profile do |f| %>
    <% if @profile.errors.any? %>
    <div class="error_messages">
      <h2>Form is invalid</h2>
      <ul>
        <% for message in @profile.errors.full_messages %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
        <%= f.label :height, "My height is: (cm)" %><%= f.select :height, options_for_select(140..220) %><br>
        <%= f.submit "Next" %>
<% end %>

When I do this I get the following error message:

undefined method `model_name' for NilClass:Class

Thanks,
TimmyOnRails

Re: Handling a form which belongs to a different model

I would take a look at http://api.rubyonrails.org/classes/Acti … thods.html and http://railscasts.com/episodes/196-nest … rm-revised.

Re: Handling a form which belongs to a different model

Thank you themusicman, that's exactly what I was looking for!