Daniel
Daniel

Reputation: 225

Rails nested form for belongs_to

I'm new to Rails and have some troubles with creating a nested form.

My models:

class User < ActiveRecord::Base
  belongs_to :company
  accepts_nested_attributes_for :company, :reject_if => :all_blank
end

class Company < ActiveRecord::Base
  has_many :users
end

Now I would like to create a new company from the user sign_up page (I use Devise, BTW) by given only a company name. And have a relation between the new User and new Company.

In the console I can create a company for an existing user like this:

@company = User.first.build_company(:name => "name of company")
@company.save

That works, but I can't make this happen for a new user. In my new user sign_up form I tried this (I know its wrong by creating a new User first but I'm trying to get something working here.)

<%= simple_form_for(resource, :as => resource_name, :html => { :class => 'form-horizontal' }, :url => registration_path(resource_name)) do |f| %>
<%= f.error_notification %>

<div class="inputs">
  <% 
    @user = User.new
    company = @user.build_company()

  %>
  <% f.fields_for company  do |builder| %>
      <%= builder.input :name, :required => true, :autofocus => true %>
  <% end %>      

  <%= f.input :email, :required => true, :autofocus => true %>
  <%= f.input :password, :required => true %>
  <%= f.input :password_confirmation, :required => true %>
</div>

<div class="form-actions">
  <%= f.button :submit, :class => 'btn-primary', :value => 'Sign up' %>
</div>

I did my best to Google for a solution/ example. I found some nested form examples but it's just not clear to me how to do this.

Upvotes: 2

Views: 2464

Answers (1)

railscard
railscard

Reputation: 1848

If you using Devise - I guess in user model you have:

attr_accessible :email, :password, :password_confirmation

So, if it's true - I think this may help:

class User < ActiveRecord::Base
  belongs_to :company
  accepts_nested_attributes_for :company, :reject_if => :all_blank
  ...
  attr_accessible :email, :password, :password_confirmation, :company_attributes
end

Form:

<% resource.build_company %>
<%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= f.error_notification %>

<div class="inputs">
  <%= f.fields_for :company  do |builder| %>
      <%= builder.input :name, :required => true, :autofocus => true %>
  <% end %>      

  <%= f.input :email, :required => true, :autofocus => true %>
  <%= f.input :password, :required => true %>
  <%= f.input :password_confirmation, :required => true %>
</div>

<div class="form-actions">
  <%= f.button :submit, :class => 'btn-primary', :value => 'Sign up' %>
</div>

Upvotes: 4

Related Questions