Ruby on rails 需要为具有设计注册的用户设置关联
我们正在使用Desive进行注册和认证。我们的公司有很多用户,而用户只有一家公司。我们希望,当用户注册时,从他们的电子邮件中提取域,使用它来标识他们的公司,并在创建用户之前将此新用户与该公司关联 我们已尝试劫持RegistrationController中的create方法:Ruby on rails 需要为具有设计注册的用户设置关联,ruby-on-rails,ruby,devise,Ruby On Rails,Ruby,Devise,我们正在使用Desive进行注册和认证。我们的公司有很多用户,而用户只有一家公司。我们希望,当用户注册时,从他们的电子邮件中提取域,使用它来标识他们的公司,并在创建用户之前将此新用户与该公司关联 我们已尝试劫持RegistrationController中的create方法: def create super do |user| company = Registrations::FindcompanyByEmailDomain.call(user.email) if comp
def create
super do |user|
company = Registrations::FindcompanyByEmailDomain.call(user.email)
if company
user.company = company
user.save
end
end
end
但这并不理想。这似乎会影响创建后的重定向,我宁愿用另一种方式来做。有什么建议吗
以下是我们在创建用户后覆盖设计路径的尝试:
def after_sign_up_path_for(resource)
go_to_a_path # doesn't work
end
def after_inactive_sign_up_path_for(resource)
go_to_another_path #also doesn't work
end
我们还尝试使用
创建前:获得公司
def get_company
self.company = FindCompanyByDomain(domain)
end
与用户模型中的保存之前的相同,使用一些魔术更新user.company
,但当设备控制器执行其操作时,两个钩子都会被忽略(binding.pry
)
任何帮助都将不胜感激
谢谢。最后,我们推翻了Desive controller中的一种方法:
# POST /resource
def create
build_resource(sign_up_params)
resource_saved = resource.save
yield resource if block_given?
if resource_saved
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_flashing_format?
sign_up(resource_name, resource)
respond_with resource, location: after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format?
expire_data_after_sign_in!
respond_with resource, location: after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
@validatable = devise_mapping.validatable?
if @validatable
@minimum_password_length = resource_class.password_length.min
end
respond_with resource
end
end
我们正在努力,因为控制器会在执行任何其他操作之前尝试保存用户,因此我们唯一需要改变的机会是创建我们自己的build\u资源
方法:
def build_resource(user_params)
super.tap do |user|
user.company = Registrations::FindCompanyByEmailDomain.call(user.email)
end
end
这允许我们将关联公司的用户模型传递给super并解决我们的问题 您能否准确显示您在回调中所做的操作?是的,再次使用该代码进行更新。您可以尝试覆盖保存
,并检查用户是否保持了。
。如果您不希望在每次保存用户时都检查此项,并且您的用户是可确认的,那么您可以覆盖确认代码>。这经常用于向新确认的用户发送欢迎电子邮件。