ruby-on-rails - 如何在用户完成帐户设置之前锁定整个 Rails 应用程序
问题描述
我有一个使用Clearance进行注册和登录的 Rails 应用程序。注册后,用户将被重定向到accounts/new
以完成其帐户设置。帐户belongs_to
用户和用户has_one
帐户。(Account 和 User 模型是分开的,因为有一些属性,例如我不想放入 User 模型中的“公司名称”。)
accounts/new
如果他们在创建帐户之前尝试访问营销页面、注册和登录页面以外的任何内容,我想锁定应用程序中的所有内容并将它们重定向到。
我认为将 a 添加before_action
到 ApplicationController 是正确的方法,然后在创建帐户之前使用他们需要访问:skip_before_action
的任何controller#action
内容(例如 /signup 或 /login 或营销页面)。
这似乎是正确的方法,因为如果用户尚未创建帐户,则默认情况下整个应用程序将被锁定。通过根据需要显式使用 using :skip_before_action
,似乎不太可能在应用程序中错误地创建漏洞。
但是我无法before_action
在 ApplicationController 上工作,因为当我访问 /signup 之类的页面时,我不断收到此错误:
NoMethodError in Clearance::UsersController#new
undefined method `account' for nil:NilClass
我正在尝试做这样的事情:
class ApplicationController < ActionController::Base
include Clearance::Controller
before_action :require_login
before_action :require_account
private
def require_account
if current_user.account != nil
redirect_to dashboard_path
end
end
end
当我在 AccountsController 中并只是重定向我的accounts#new
操作时,该语法有效,但现在我无法弄清楚如何在整个应用程序中获得相同的行为。注意:current_user
是 Clearance 提供的一种方法。
执行此操作的“Rails 方式”是什么?
解决方案
如果我理解正确,我认为您以“Ruby on Rails 方式”的正确方式来做这件事!
导致该错误NoMethodError
的原因是在您的应用程序的某些上下文中您没有该current_user
方法。
如果您想将用户重定向到dashboard_path
current_user 已经拥有帐户时,您应该尝试以下操作:
class ApplicationController < ActionController::Base
include Clearance::Controller
before_action :require_login
before_action :require_account
private
def require_account
if current_user && current_user.account.present?
redirect_to dashboard_path
end
end
end
这样,您可以在current_user is present
AND current_user have one account
不需要时获得重定向skip_before_action
。
推荐阅读
- vue.js - Echarts OnClick 方法没有到达 Vue 中的外部方法
- java - 使用 lambda (:: operator) 调用方法引用
- css - 是否有一个属性可以对图像标签执行“背景附件:固定”对背景图像的作用?
- r - 填充 R 向量中的小时-分钟间隙
- reactjs - React useState:对象作为状态,如何通过替换和避免cancat来更新字符串值?
- python - 精灵组中的一些对象卡在屏幕上而不是在 pygame 中移动
- amazon-web-services - Security Hub 调查结果 - 识别资源 ID
- python - Gorm 是否支持数据迁移?
- kubernetes - K8s pod 继承不适用于 k8s secret
- c# - IdentityModel 实施:如何在到期日或之后验证(和刷新)access_token?