【发布时间】:2019-04-03 16:45:48
【问题描述】:
我有一个使用Clearance 进行注册和登录的rails 应用程序。注册后,用户将被重定向到accounts/new 以完成他们的帐户设置。帐户belongs_to 用户和用户has_one 帐户。 (Account 和 User 模型是分开的,因为有一些属性,例如我不想放入 User 模型中的“公司名称”。)
如果他们在创建帐户之前尝试访问营销页面、注册和登录页面以外的任何内容,我想锁定应用程序中的所有内容并将它们重定向到 accounts/new。
我认为向 ApplicationController 添加before_action 是正确的方法,然后在创建帐户之前需要访问的任何controller#action 上使用:skip_before_action(例如/signup 或/login 或营销页面)。
这似乎是正确的方法,因为如果用户尚未创建帐户,则默认情况下整个应用程序将被锁定。通过根据需要显式使用:skip_before_action,似乎不太可能在应用程序中错误地创建漏洞。
但我无法让 ApplicationController 上的 before_action 工作,因为我在访问 /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 方式”是什么?
【问题讨论】:
-
SignInGuard 呢?
标签: ruby-on-rails ruby model-view-controller actioncontroller clearance