MouMohsen
MouMohsen

Reputation: 53

Devise: Add User Details in different table

I have two models User and Person

I want to stick with the default table for the user offered by Devise to include only email and password and add User details in Person

Here is my models

class Person < ApplicationRecord   
belongs_to :user 
end

User Model

 class User < ApplicationRecord
    ...
    has_one :person
    ...
 end

I also override RegistrationController.rb to look like this

class RegistrationsController < Devise::RegistrationsController

  def sign_up_params
  params.require(:user).permit(:first_name, :email, :password, :password_confirmation)
end

end

and here is the view

<h2>Sign up</h2>

<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= f.error_notification %>
  <%= f.fields_for :person do |p| %>
  <%= p.text_field :first_name %>
  <%= p.text_field :last_name %>
  <% end %>

  <div class="form-inputs">
    <%= f.input :email, required: true, autofocus: true %>
    <%= f.input :password, required: true, hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length) %>
    <%= f.input :password_confirmation, required: true %>
  </div>

  <div class="form-actions">
    <%= f.button :submit, "Sign up" %>
  </div>
<% end %>

<%= render "devise/shared/links" %>

With the code it didn't work, and it didn't update the people column while registration

How Can I get devise to add details in two models using the only one form offered by devise ? To add email and password in Users Table and other details e.g. first_name in People Table

Upvotes: 1

Views: 1236

Answers (2)

Oleksandr Avoiants
Oleksandr Avoiants

Reputation: 1929

Nested-Models setup for simple_form

Add accepts_nested_attributes_for to User model

class User < ActiveRecord::Base
  has_one :person
  accepts_nested_attributes_for :person
end

Update permit params in controller:

class RegistrationsController < Devise::RegistrationsController
  def sign_up_params
    params.require(:user).permit(:email, :password, :password_confirmation,
      person_attributes: [:first_name, :last_name])
  end
end

Change f.fields_for :person to f.simple_fields_for :person in view.

Check https://github.com/plataformatec/simple_form/wiki/Nested-Models

Upvotes: 1

Darpan Chhatravala
Darpan Chhatravala

Reputation: 520

You need to set strong params inside your controller private method as per below:

def sign_up_params
  params.require(:user).permit(:first_name, :email, :password, :password_confirmation, person_attributes: [:person_model_attributes])
end

Inside your User model add below line:

accepts_nested_attributes_for :person

Upvotes: 0

Related Questions