简体   繁体   English

控制器Rails 5未调用Before_Action

[英]Before_Action not being called for controller Rails 5

I'm currently trying to redirect user accounts who have user.account_delinquent = true . 我目前正在尝试重定向具有user.account_delinquent = true用户帐户。 The issue is, the account is still able to access the test controller even though the helper method is active. 问题是,即使辅助方法处于活动状态,该帐户仍能够访问测试控制器。

My controller has included ApplicationHelper with a before_action :account_delinquency , but the method refuses to fire. 我的控制器已经将ApplicationHelper包含在before_action :account_delinquency ,但是该方法拒绝触发。

How can I properly setup my account_delinquency helper method to fire a redirect if the current_user.account_delinquent == true ? 如果current_user.account_delinquent == true如何正确设置我的account_delinquency帮助器方法来触发重定向?

My code is below: 我的代码如下:

magazines_controller.rb magazines_controller.rb

class MagazinesController < ApplicationController
  include ApplicationHelper
  before_action :account_delinquency

  def index
    @magazines = Magazine.all
  end
end

application_helper.rb application_helper.rb

def account_delinquency
  if user_signed_in? || employer_signed_in?
    redirect_to update_account_index_path, alert: 'We were unable to charge your account' if current_user.account_delinquent == true || current_employer.account_delinquent == true
  end
end

Try defining account_delinquency in ApplicationController , not in ApplicationHelper . 尝试在ApplicationController中而不是ApplicationHelper定义account_delinquency I always put before actions in a controller, never in a helper. 我总是将动作放在控制器中,而不放在助手中。

I managed to get the helper method working by syncing the user_session to the user variable itself. 我设法通过将user_session与用户变量本身同步来使辅助方法起作用。 Since, this method will only be used for logged in members. 从此以后,此方法将仅用于登录成员。

application_helper.rb application_helper.rb

def account_delinquency
    @current_user ||= User.find_by_session(session[:user_id])
    redirect_to update_account_index_path, alert: 'We were unable to charge your account' if @current_user.account_delinquent
  end

controller.rb controller.rb

class MagazinesController < ApplicationController
    include ApplicationHelper
    before_action :account_delinquency
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM