Using Ruby on Rails, I want to before filter an action but only when users are logged in.
How is this possible?
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.
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.
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.
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
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
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? }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With