如何在多类型用户的多态关联中创建记录



我对多种类型的用户(adminoriginal_user(有多态关联。

我需要创建一个具有相关模型的所有属性的用户注册,但我只能在相关表中创建记录的ID,例如Admin或OriginalUser。

如果我有嵌套的属性,我该怎么做?

在终端中调试代码时,我看到:

Unpermitted parameter: :admin_attributes

而CCD_ 3只有

{"email"=>"ush@gmail.com", "password"=>"123456", "password_confirmation"=>"123456", "meta_type"=>"admin"}

没有CCD_ 4。

admin的属性为"degree_access"(整数(、"department"(字符串(。

原始用户的属性为first_name(字符串(、last_name(字符串(和team(字符串(。

app/models/user.rb:

class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :tasks, dependent: :destroy
belongs_to :meta, polymorphic: true, validate: true
accepts_nested_attributes_for :meta
end

app/models/admin.rb:

class Admin < ApplicationRecord
has_one :user, as: :meta, dependent: :destroy
end

app/models/original_user.rb:

class OriginalUser < ApplicationRecord
has_one :user, as: :meta, dependent: :destroy
end

app/controllers/users/registrations_controller.rb:

module Users
class RegistrationsController < Devise::RegistrationsController
before_action -> { request.session_options[:skip] = true }
before_action :configure_sign_up_params
KEYS_FOR_SIGNUP = %i[
meta_type
email
password
password_confirmation
[ admin_attributes: [ :degree_access, :department] ]
[ original_user_attributes: [:first_name, :last_name, :team] ]
].freeze
def create
build_resource(sign_up_params)
if resource.meta_type == 'admin'
resource.meta = Admin.new
elsif resource.meta_type == 'original_user'
resource.meta = OriginalUser.new
end
if resource.save
render json: resource.payload
else
render json:
bad_request_params(resource.errors), status: :bad_request
end
end
protected
def configure_sign_up_params
devise_parameter_sanitizer.permit(:sign_up,
keys: KEYS_FOR_SIGNUP)
end
end
end

我认为你不能使用这个方案

KEYS_FOR_SIGNUP = %i[
meta_type
email
password
password_confirmation
[ admin_attributes: [ :degree_access, :department] ]
[ original_user_attributes: [:first_name, :last_name, :team] ]
].freeze

因为您将得到CCD_ 10而不是预期的行为。必须使用不带文字%i的纯数组

最新更新