Don P
Don P

Reputation: 63758

A controller before_filter has no effect

In Rails 4, I use before_action :require_login for my UserController. This is supposed to redirect if the user is not logged in. However the filter doesn't seem to be used. Why?

require_login is defined in app/helpers/sessions_helper.rb. So it is not a helper for my controller UsersController.

How does UserController know to use the function from sessions_helper.rb? It seems like I should be more specific: before_action "session/require_login".

The controller in users_controller.rb:

class UsersController < ApplicationController
  before_action :signed_in_user

  def index
  end
end

The helper function in sessions_helper.rb:

  def require_login
    unless signed_in?
      store_location
      redirect_to signin_url, notice: "Please sign in." unless signed_in?
    end
  end

Upvotes: 1

Views: 80

Answers (2)

sevenseacat
sevenseacat

Reputation: 25049

You're following Michael Hartl's tutorial? Helpers in /app/helpers designed for view logic, not for controller code.

However, to get the helper included into your controllers you can use include SessionsHelper.

Reference: http://ruby.railstutorial.org/chapters/sign-in-sign-out#code-sessions_helper_include

Upvotes: 3

Billy Chan
Billy Chan

Reputation: 24815

before_filter can only call controller method, not helper.

You need to move the helper require_login from helper to UsesController or its parent say ApplicationController.

If you still want to use require_login as a helper in view, you can expose it from controller by helper_method

class UsersController < ApplicationController
  before_fitler :require_login
  helper_method :require_login

  def require_login
    # code
  end
end

Upvotes: 1

Related Questions