can't make sign up register my profile data and user data on two different tables on Rails - Devise

26 Views Asked by At

I've been trying to register an user and save his profile data on another table because I have different types of them. When they register they are asked for different fields depending on what they are (a client, business, etc.) I can't make it work. Here are my models

 class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_one :cliente, dependent: :destroy
  before_create :build_cliente
  accepts_nested_attributes_for :cliente

end

And the cliente model

class Cliente < ApplicationRecord
    belongs_to :user
end

My Application controller

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  before_action :authenticate_user!

  before_action :configure_permitted_parameters, if: :devise_controller?

  protected
  def configure_permitted_parameters
        devise_parameter_sanitizer.permit(:sign_up, keys: [address_attributes: [:nombre, :apellidos]])
end
end

The form:

<h2>Sign up</h2>

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

  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true, autocomplete: "email" %>
  </div>

  <div class="field">
    <%= f.label :password %>
    <% if @minimum_password_length %>
    <em>(<%= @minimum_password_length %> characters minimum)</em>
    <% end %><br />
    <%= f.password_field :password, autocomplete: "off" %>
  </div>

  <div class="field">
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "off" %>
  </div>

<%= f.fields_for :cliente do |cliente_form| %>
  <div class="form-group">
    <%= cliente_form.text_field :nombre, class: "form-control", placeholder: "nombre" %>

    <%= cliente_form.text_field :apellidos, class: "form-control", placeholder: "apellidos" %>
  </div>
<% end %>

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

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

I don't know why but it makes a register on the table clientes, but it only has the default id and the user_id which is properly referenced. I'm new to rails and to coding in general. I'm a little lost. Any help would be appreciated. Also, I know my english is a little rusty, hope you understand the post.

1

There are 1 best solutions below

1
Pak On

It looks mostly right, your strong parameters should probably be cliente_attributes though. See http://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters