【问题标题】:How to lock down an entire Rails app until a User completes their account set up如何在用户完成帐户设置之前锁定整个 Rails 应用程序
【发布时间】: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 方式”是什么?

【问题讨论】:

标签: ruby-on-rails ruby model-view-controller actioncontroller clearance


【解决方案1】:

如果我理解正确,我认为您在“Ruby on Rails 方式”中的做法是正确的!

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

如果您想在 current_user 已经拥有帐户的情况下将用户重定向到dashboard_path,您应该尝试以下操作:

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

【讨论】:

  • 我认为条件可以缩短为if current_user&amp;.account
  • 好评!我写current_user &amp;&amp; current_user.account.present? 只是为了提高阅读效果,在实际情况下我更喜欢if current_user&amp;.account
  • 谢谢!预期的行为实际上是if current_user &amp;&amp; current_user.account.blank? 但这绝对帮助我到达那里。这是我最终得到的应用程序控制器 - gist.github.com/leemcalilly/68ca89f3c9e193266c9b9d9287263978。和帐户控制器gist.github.com/leemcalilly/78efdde8efd092c24e754e021788ec4e。此外,另一个导致问题的“陷阱”是我必须将我的路线从get '/signup' =&gt; 'clearance/users#new', as: 'sign_up' 更新为get '/signup' =&gt; 'users#new', as: 'sign_up',以便我可以跳过注册/登录之前的操作。
猜你喜欢
  • 2013-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2010-11-30
  • 1970-01-01
  • 2011-01-05
  • 2012-01-31
相关资源
最近更新 更多