Greg
Greg

Reputation: 34818

before_filter syntax when you want to "except" controller "abc"

In Rails what is the before_filter syntax when you want to "except" controller "abc".

Example, in the application_controller if I want to say:

before_filter :login_required :except => ["-name of controller-"]

Background - Just wanted basic authentication across the whole app except the controller that actually handles getting a user authenticated....

Upvotes: 27

Views: 19123

Answers (3)

Marnen Laibow-Koser
Marnen Laibow-Koser

Reputation: 6337

Instead of using the controller name, I'd recommend taking advantage of the fact that controllers inherit their filters from their parent. So what I'd recommend is something like this:

# app/controllers/application_controller.rb
class ApplicationController
  # no filters here
end

# app/controllers/authenticated_controller.rb
class AuthenticatedController < ApplicationController
  before_filter :login_required
end

# app/controllers/some_other_controller.rb
class SomeOtherController < AuthenticatedController
  # inherits the before_filter from AuthenticatedController
  # use this for most of your other controllers
end

# app/controllers/unauthenticated_controller.rb
class UnauthenticatedController < ApplicationController
  # no filters, since this inherits directly from ApplicationController
  # use this for the controller that you don't want to check login on
end

This means controllers know whether they're supposed to check login, rather than having a (possibly brittle) list of names.

Upvotes: 3

Baldrick
Baldrick

Reputation: 24340

You can put the following line in the controller where the before_filter should not be executed:

skip_before_filter :login_required

You can even specifiy the methods where the before_filter is ignored with :only and :except options:

skip_before_filter :login_required, :only => [:login]

An example here.


Edit: with Rails 4, before_filter is aliased with before_action, and skip_before_filter is also aliased with skip_before_action

Upvotes: 59

monangik
monangik

Reputation: 366

The before_filter syntax is

before_filter :login_required, :except => ["-name of the action-"]

Have a look on Rails API Doc.

Upvotes: 14

Related Questions