user3443619
user3443619

Reputation: 119

Rails Devise Simple_form nested 2 models on submit

I have one form where you can sign up as a regular user and another form to create a 'company' once you're signed up. But I want to create a 'third' form where you can create a company and a new user in one, so I need to create on both models.

_form.html.erb

<%= simple_form_for(@company) do |f| %>
 <% if @company.errors.any? %>
<div id="error_explanation">
  <h2><%= pluralize(@company.errors.count, "error") %> prohibited this company from being saved:</h2>

  <ul>
  <% @company.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
  <% end %>
  </ul>
 </div>
<% end %>

<div class="field">
 <%= f.label :name %><br>
 <%= f.text_field :name, :class => "input-txt form-control" %>
</div>
<div class="field">
 <%= f.label :address %><br>
 <%= f.text_area :address, :class => "input-txt form-control" %>
</div>
<div class="field">
 <%= f.label :business_phone %><br>
 <%= f.text_field :business_phone, :class => "input-txt form-control" %>
</div>
<div class="field">
 <%= f.label :cell_phone %><br>
 <%= f.text_field :cell_phone, :class => "input-txt form-control" %>
</div>

<% if user_signed_in? %>

<div class="actions">
 <%= f.submit %>
</div>

<% else %>

 <% simple_fields_for(@users) do |f| %>

      <p><%= f.label :email%><br/>
        <%= f.email_field :email, :class => "input-txt form-control" %>
      </p>

      <p><%= f.label :password %><br />
        <%= f.password_field :password, :class => "input-txt form-control" %>
      </p>

      <p><%= f.label :password_confirmation %><br />
        <%= f.password_field :password_confirmation, :class => "input-txt form-control" %>
      </p>

<div class="actions">
  <%= f.submit %>
</div>
<% end %>

<% end %>

<% end %>

company.rb

class Outfitter < ActiveRecord::Base
has_many :users

accepts_nested_attributes_for :users
end

user.rb

belongs_to :company

It should show the User input fields and submit button if a user is not already signed in but it does not, it just shows the company input fields. I get 'undefined method `model_name' for NilClass:Class'

Upvotes: 0

Views: 269

Answers (1)

Ross Nelson
Ross Nelson

Reputation: 829

If there are no user records associated with the outfitter simple_fields_for will not display a user . In your controller do this:

def new
  @outfitter = Outfitter.new
  @outfitter.users.build
end

This will create a blank user record within the @outfitter users relation.

Then in your view change simple_fields_for(@user) to simple_fields_for :users

Upvotes: 1

Related Questions