Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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....

like image 343
Greg Avatar asked Feb 20 '12 20:02

Greg


3 Answers

The before_filter syntax is

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

Have a look on Rails API Doc.

like image 20
monangik Avatar answered Nov 10 '22 06:11

monangik


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

like image 148
Baldrick Avatar answered Nov 10 '22 05:11

Baldrick


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.

like image 23
Marnen Laibow-Koser Avatar answered Nov 10 '22 05:11

Marnen Laibow-Koser