简体   繁体   中英

Before_Action not being called for controller Rails 5

I'm currently trying to redirect user accounts who have 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.

How can I properly setup my account_delinquency helper method to fire a redirect if the current_user.account_delinquent == true ?

My code is below:

magazines_controller.rb

class MagazinesController < ApplicationController
  include ApplicationHelper
  before_action :account_delinquency

  def index
    @magazines = Magazine.all
  end
end

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 . 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. Since, this method will only be used for logged in members.

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

class MagazinesController < ApplicationController
    include ApplicationHelper
    before_action :account_delinquency
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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