我正在尝试根据用户的电子邮件域将用户分配到他们的公司组。我正在使用设计+确认,所以我避免使用正则表达式(不需要验证它是一个有效的电子邮件...),并试图以一种简单的方式做到这一点。基本上,它会强制用户company_id(与该表匹配)在注册时分配,然后如果他们的公司不存在则不允许他们注册。因此,这适用于test@company.com和test@recruiting.company.com
在用户模型中
before_create :company_placement
...
def company_placement
user_domain = (:email).split('@').last
while user_domain.split('.').count > 2
user_domain = user_domain.split('.', 2).last
end
if Company.find_by_domain(user_domain) != nil
(:company_id) = Company.find_by_domain(user_domain).id
else
#error out
end
end
当我在rails控制台中逐步执行此操作时,似乎可以正常工作。但是当我跑步时,在控制台中,
> user = User.create!(name: "test", email: "test@example.com", password: "foobar")
我为#<'User ....
获取未定义的局部变量或方法'user'感谢您的帮助,还在学习铁路......
答案 0 :(得分:1)
所以我更多地玩这个,并认为我找到了一个我喜欢的解决方案
用户模型中
before_validation :company_placement
...
def company_placement
user_domain = self.email.split('@').last
while user_domain.split('.').count > 2
user_domain = user_domain.split('.', 2).last
end
if Company.find_by_domain(user_domain) != nil
self.company_id = Company.find_by_domain(user_domain).id
end
end
创建设计注册控制器 - 控制器/注册 _ controller.rb
新注册控制器中的
class RegistrationsController < Devise::RegistrationsController
before_filter :verify_company, only: :create
private
def verify_company
build resource #necessary for devise
user_domain = resource.email.split('@').last
while user_domain.split('.').count > 2
user_domain = user_domain.split('.', 2).last
end
unless Company.find_by_domain(user_domain) != nil
flash[:error] = 'Sorry, your company does not exist yet'
redirect_to root_path
end
end
end
<强>的routes.rb 强>
devise_for :users, :controllers => { :registrations => "registrations" }
所以我确定有更优雅的解决方案,但这对我有用。处理控制器中的错误/闪存,然后如果公司存在,则用户通过模型自动分配给公司。