首页 > 解决方案 > 无法在 Rails 上的两个不同表上注册我的个人资料数据和用户数据 - 设计

问题描述

我一直在尝试注册用户并将他的个人资料数据保存在另一个表上,因为我有不同类型的用户。当他们注册时,根据他们的身份(客户、企业等),他们会被要求提供不同的字段。我无法让它发挥作用。这是我的模型

 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

和客户模型

class Cliente < ApplicationRecord
    belongs_to :user
end

我的应用程序控制器

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

表格:

<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" %>

我不知道为什么,但它在表客户端上进行了注册,但它只有默认 id 和正确引用的 user_id。我是 Rails 和一般编码的新手。我有点失落。任何帮助,将不胜感激。另外,我知道我的英语有点生疏,希望你能理解这篇文章。

标签: ruby-on-railsauthenticationdevisemodelsrole

解决方案


它看起来基本正确,但您的强参数可能应该是 cliente_attributes。请参阅http://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters


推荐阅读