I'm trying to implement a dual registration (users can be either customers or providers) with Devise, but I'm getting nowhere (>_<).
So I have a sign up link with a parameter http://localhost:3000/users/sign_up?type=customer and http://localhost:3000/users/sign_up?type=provider
My problem is that if I put the nested form with :provider like <%= f.fields_for :provider do |fp| %>
as I expect it to be, because is an has_one association it isn't shown. And if I put it with :providers like <%= f.fields_for :providers do |fp| %>
the field is properly shown in the form, but it is not saved.
I tried some of the proposed things in other posts (like this and this), but nothing seems to work for me...
Here is a simplified version of my code:
Routes:
Rails.application.routes.draw do
devise_for :users, :controllers => { registrations: 'registrations' }
resources :users
resources :customers
resources :providers
end
Models:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_one :customer
accepts_nested_attributes_for :customer
has_one :provider
accepts_nested_attributes_for :provider
end
class Customer < ActiveRecord::Base
belongs_to :user
end
class Provider < ActiveRecord::Base
belongs_to :user
end
Controllers:
class RegistrationsController < Devise::RegistrationsController
def sign_up_params
params.require(resource_name).permit(:email, :password, :password_confirmation, customer: [:field_x], :provider: [:field_y]))
end
end
Views:
<h2>Sign up</h2>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
...
<% if params[:type] == "customer" %>
<%= f.fields_for :customers do |fc| %>
<div class="field">
<%= fc.label :field_x %><br />
<%= fc.text_field :field_x, autofocus: true %>
</div>
<% end %>
<% end %>
<% if params[:type] == "provider" %>
<%= f.fields_for :providers do |fp| %>
<div class="field">
<%= fp.label :field_y %><br />
<%= fp.text_field :field_y, autofocus: true %>
</div>
<% end %>
<% end %>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
Thanks a lot!