Luc
Luc

Reputation: 17082

How to build a devise nested resource during registration?

During registration of a new user with Devise, I need to create a new Family object link to this new user at the same time (the user being the head of the family).

My family model:

belongs_to user

My user model:

attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :family
has_one :family
accepts_nested_attributes_for :family

In devise/registration/new.html.erb

<%= simple_form_for([resource, Family.new], :as => resource_name, :url =>     registration_path(resource_name), :html => {:class => 'form-vertical' }) do |f| %>
  <%= f.error_notification %>
  <%= display_base_errors resource %>
  <%= f.input :name, :autofocus => true %>
  <%= f.input :email, :required => true %>
  <%= f.input :password, :required => true %>
  <%= f.input :password_confirmation, :required => true %>

  <% f.fields_for :family do |family_form| %>
    <p><%= family_form.label :name %></p>
    <p><%= family_form.text_field :name %></p>
  <% end %>

  <%= f.button :submit, 'OK', :class => 'btn-primary' %>
<% end %>

But this is not working, I find a couple of question like this but I did not manage to fix that.

Any idea ?

UPDATE 1

I got the following error:

undefined method `email' for #<Family:0x007f892a12c310>

Family is a model that do not have any email, just a name. I just need to be able to create a new Family object with a name when creating a new user (and link it to the user as well).

UPDATE 2

I have added resource.build_family in my registrations controller. The family object is correctly created and associated to the user (I can display <%= resource.family %> in new.html.erb for debugging), but still no form displayed for the family.

Upvotes: 3

Views: 1169

Answers (2)

thisismydesign
thisismydesign

Reputation: 25182

If you're getting undefined method 'email' for #<Model:0x007f892a12c310>:

You need to overwrite Devise::RegistrationsController as described in the docs: https://github.com/heartcombo/devise#configuring-controllers. E.g.

class Users::RegistrationsController < Devise::RegistrationsController
  def new
    super do |resource|
      resource.build_<model>
    end
  end
end

And you must only specify resource in form_for: simple_form_for(resource, ... instead of simple_form_for([resource, Model.new], ...

Upvotes: 0

Mark Stratmann
Mark Stratmann

Reputation: 1612

You need the equal sign in the <%=fields_for

<%= f.fields_for :family do |family_form| %>
    <p><%= family_form.label :name %></p>
    <p><%= family_form.text_field :name %></p>
  <% end %>

And in your user model you need to make the :family_attribues accessible and not :family

attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :family_attributes
has_one :family
accepts_nested_attributes_for :family

Upvotes: 1

Related Questions