Johnny C
Johnny C

Reputation: 131

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

Upvotes: 2

Views: 1626

Answers (2)

Johnny C
Johnny C

Reputation: 131

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

Upvotes: 0

Brian Morearty
Brian Morearty

Reputation: 3348

Try defining account_delinquency in ApplicationController, not in ApplicationHelper. I always put before actions in a controller, never in a helper.

Upvotes: 1

Related Questions