Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails :before_filter => :only_when_user_is_logged_in

Using Ruby on Rails, I want to before filter an action but only when users are logged in.

How is this possible?

like image 304
thenengah Avatar asked Dec 13 '09 05:12

thenengah


People also ask

What does before_ filter do in rails?

before_filter and around_filter may halt the request before a controller action is run. This is useful, for example, to deny access to unauthenticated users or to redirect from HTTP to HTTPS. Simply call render or redirect. After filters will not be executed if the filter chain is halted.

What is around_ filter in rails?

There are three types of filters implemented in Rails: a before_filter runs before the controller action. an after_filter runs after the controller action. an around_filter yields to the controller action wherever it chooses.

What is around filter?

Around Filters. Rails around filters contain codes that are executed both before and after controller's code is executed. They are generally used when you need both before and after filter. Its implementation is little bit different and more complex than other two filters.


3 Answers

before_filter :only_when_user_is_logged_in, :only => :the_action

Or for multiple

before_filter :only_when_user_is_logged_in, :only => [:the_action, :another_action]

On the flip side, you can also provide an :except => :this_action option

like image 67
nowk Avatar answered Nov 15 '22 21:11

nowk


I think you're asking how to run a before filter only if a user is logged in. There is no built-in semantic for this, but it's easy enough to inline:

class SomeController < ApplicationController
  before_filter :do_something

  def do_something
    if logged_in?
      # the stuff you want to do
    end
  end
end
like image 24
Michael Bleigh Avatar answered Nov 15 '22 20:11

Michael Bleigh


Before filters take an optional block which is passed the current controller instance so you could do something like this:

before_filter :do_stuff, lambda { |controller| controller.logged_in? }
like image 35
pmh Avatar answered Nov 15 '22 21:11

pmh