首页 > 解决方案 > 如何在用户完成帐户设置之前锁定整个 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-railsrubymodel-view-controlleractioncontrollerclearance

解决方案


如果我理解正确,我认为您以“Ruby on Rails 方式”的正确方式来做这件事!

导致该错误NoMethodError的原因是在您的应用程序的某些上下文中您没有current_user方法。

如果您想将用户重定向到dashboard_pathcurrent_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


推荐阅读