我有一个使用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 方式”是什么?