0

I have a controller named HomeController with index and show actions. I want to check if the user subscription has ended and show him a message and redirect to HomeController#index.

Currently i am doing it as below

class HomeController < ApplicationController

  before_action :check_if_trial_expired, only: [:index]
  before_action :redirect_if_trial_expired, only: [:show]
 
  protected

  def check_if_trial_expired
    @trial_expired = current_user.trial_expired?
  end

  def redirect_if_trial_expired
    redirect_to home_path if current_user.trial_expired?
  end
end

Is there a better way to do this? I want to redirect the user to HomeController#index in case a condition satisfies.

Many Thanks in advance.

4

1 回答 1

0

您至少需要控制器上定义的indexshow方法;确保您的路线中有它们。我认为您不需要使用before_action索引。此外,trial_expired如果这是一项昂贵的操作,您可以记忆。

class HomeController < ApplicationController
  before_action :redirect_if_trial_expired, only: [:show]

  def index; end

  def show; end
 
  private

  def redirect_if_trial_expired
    redirect_to home_path if current_user.trial_expired?
  end
end

于 2021-04-08T12:44:31.150 回答