Friday, September 2, 2011

The nest of despair

I've recently had the need to add a supplemental model to a user when they sign up, based on the signup info they provide.

For instance, if a user signs up the have to at least provide

email
password
password confirmation

However I also wanted to be able to register corporate users, so they can optionally supply

company name
and
company url
Enter accepts_pain, I mean accepts_nested_attributes_for.

This is in principle a very good idea and should make implementing this sooo easy.

So, here is my model before I add it in:

class User < ActiveRecord::Base
   has_one :company
   devise :registerable #keeping it simple here
   validates :email, :presence => true
   attr_accesible :email, :password, :password_confirmation
end

and here is the model after...


class User < ActiveRecord::Base
   has_one :company
   devise :registerable #keeping it simple here
   validates :email, :presence => true
   attr_accessible :email, :password, :password_confirmation, :company_attributes
   accepts_nested_attributes_for :company
end
At this point I should point out that you have to put accepts_asshattery after the association is defined. So in this case, after has_one :company

Ok now on to the views, and here is where the pain started.

A normal view from devise might look like this:

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <%= f.label :email %>
  <%= f.email_field :email %>

  <%= f.label :password %>
  <%= f.password_field :password %>

  <%= f.label :password_confirmation %>
  <%= f.password_field :password_confirmation %> 

  <%= f.submit "Sign up" %>
<% end %>

To get nested magic, you have to add the nested fields...
  ...
  <%= devise_error_messages! %>

  <%= f.fields_for :company do |builder| %>
    <%= builder.label :name %>
    <%= builder.text_field :name %>

    <%= builder.label :url %>
    <%= builder.url_field :url %>
  <% end %>
   
  <%= f.label :email %>
  <%= f.email_field :email %>

  ...

This however, had me running around in circles for a good long while, so I'll cut to the chase to you: The nested form requires you to specify "company_attributes" not just ":company"

The error is not, I dare say, very apparent.  In my case the User model was firing off several after_create handlers, and they were all fine. Just company never created. no failure, just not call at all.

The API docs were not much help, and pointed my in the intuitive but wrong direction:

This model can now be used with a nested fields_for, like so:
<%= form_for @person do |person_form| %>
  ...
  <%= person_form.fields_for :address do |address_fields| %>
    Street  : <%= address_fields.text_field :street %>
    Zip code: <%= address_fields.text_field :zip_code %>
  <% end %>
  ...
<% end %>
So there.

No comments:

Post a Comment