我目前正在尝试重定向user.account_delinquent = true
的用户帐户。问题是,即使帮助程序方法处于活动状态,该帐户仍能够访问测试控制器。
我的控制器包含带有before_action :account_delinquency
的ApplicationHelper
,但该方法拒绝触发。
如果current_user.account_delinquent == true
,如何正确设置我的account_delinquency
帮助程序方法来触发重定向?
我的代码如下:
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
尝试在ApplicationController
中定义account_delinquency
,而不是在ApplicationHelper
中定义。我总是在控制器中先于操作,从不在帮助程序中。
我设法通过将user_session同步到用户变量本身来使帮助程序方法工作。因为,此方法将仅用于登录成员。
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
控制器.rb
class MagazinesController < ApplicationController
include ApplicationHelper
before_action :account_delinquency
end