4

I am trying to get my user form to also allow the user to fill out their company profile at the same time via form_for. For some reason it is not showing the company fields. Here is my code for the controller and layouts.

class User < ActiveRecord::Base
  attr_accessible :company_attributes

  has_one :company
  accepts_nested_attributes_for :company
end

class Company < ActiveRecord::Base
  belongs_to :user

  # Validation
  validates :name, :presence => true
end

<%= f.fields_for :company do |company_form| %>
  <div class="field">
    <%= company_form.label :name, "Company Name" %><br />
    <%= company_form.text_field :name %>
  </div>
<% end %>
Joshua Novak
  • 144
  • 1
  • 10

3 Answers3

6

The company attribute of the User should be not-nil, so either in the controller or in the form, create it:

<% user.build_company if user.company.nil? %>
<%= f.fields_for :company do |company_form| %>
...
Zabba
  • 64,285
  • 47
  • 179
  • 207
5

It might be better to do this in the model rather than the view or the controller.

class User
  # Blah blah blah
  def profile
    super || build_profile
  end
end
sean_j_roberts
  • 430
  • 7
  • 9
  • Thank you for this! I'm working with Devise and I don't know that I can do a `resource.build_profile` in the RegistrationsController, so this worked great. – Ryan Arneson Oct 28 '13 at 19:39
0

The above solution from Zabba only worked for me with:

<% @user.build_profile if @user.profile.nil? %>

Othwerise, the view had no idea what "user" is

Sam Rose
  • 66
  • 1
  • 5