Rails-如何在Devise注册表中添加其他列值?

问题描述:

用户模型

class User < ApplicationRecord
  belongs_to :tenant, dependent: :destroy
end

租户模型

class Tenant < ApplicationRecord
    has_many :users
end

控制器

解决方法1(无效)

def create
    super

    @tenant = Tenant.new
    @user = @tenant.build_user(params)
    @tenant.save
end

变通方法2(不起作用)

Workaround 2 (not working)

def create
    @tenant = Tenant.new
    @user = User.build(params)
    @tenant.save

    super

end

是否有可能传递参数来设计超类?

Is there any possibilities to pass a parameter to devise super class?

由于Devise超级方法在用户注册/密码哈希/上具有其自身的功能,因此我无法完全覆盖该功能。

Since Devise super method has its own functionality on user registration/password hashing/, I can not completely override the function.

I知道我的储蓄方式是错误的,请向我建议更好的方法。

I know the way I am saving is wrong, please suggest me the better approach.

实际源代码:


(与Co ntroller,模型,迁移和路由文件已添加。)

(with Controller, Model, Migrations and Routes files are added.)

https://repl.it/@aravin/HarmlessRepentantHarddrive

您可以覆盖 sign_up_params 在您的控制器中:

You can override the sign_up_params in your controller:

class RegistrationsController < Devise::RegistrationsController

  private

  def sign_up_params    
    params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation...).merge({tenant_id: Tenant.create!.id})
  end
end