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?
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 really don't want the before_filter
executing for anyone other than logged in users consider using #skip_before_filter
in your authentication filter. For instance if when you're checking if users are logged in in your authentication filter, if authentication fails, merely call skip_before_filter :filter_for_logged_in_users_only
.
Other than that you can simply test if the user is logged in before executing the member only filter. For example:
def filter_for_logged_in_users_only
return true unless current_user && logged_in?
#rest of the logic
end
If you're using restful authentication, it's just before_filter :login_required
. If you are using your own authentication framework, you can create a method in application.rb that returns true if the user is logged in or redirects to the login page otherwise.
class LoginsController < ApplicationController
skip_before_filter :require_login, :only => [:new, :create]
end
精彩评论