Ruby on Rails :before_filter => :only_when_user_is_logged_in
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1895645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby on Rails :before_filter => :only_when_user_is_logged_in
提问by thenengah
Using Ruby on Rails, I want to before filter an action but only when users are logged in.
使用 Ruby on Rails,我想在过滤操作之前但仅在用户登录时过滤。
How is this possible?
这怎么可能?
回答by nowk
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_actionoption
另一方面,您还可以提供一个:except => :this_action选项
回答by Michael Bleigh
I think you're asking how to runa before filter only if a user is logged in. There is no built-in semantic for this, but it's easy enough to inline:
我认为您是在问如何仅在用户登录时才运行before 过滤器。 对此没有内置语义,但内联很容易:
class SomeController < ApplicationController
before_filter :do_something
def do_something
if logged_in?
# the stuff you want to do
end
end
end
回答by pmh
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? }
回答by andykram
If you really don't want the before_filterexecuting for anyone other than logged in users consider using #skip_before_filterin 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.
如果您真的不希望before_filter为登录用户以外的任何人执行,请考虑#skip_before_filter在您的身份验证过滤器中使用。例如,如果您在验证过滤器中检查用户是否登录时,如果验证失败,只需调用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
回答by Brian Deterling
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.
如果您使用的是 Restful 身份验证,则它只是before_filter :login_required. 如果您使用自己的身份验证框架,则可以在 application.rb 中创建一个方法,如果用户已登录则返回 true,否则会重定向到登录页面。
回答by Allwin
class LoginsController < ApplicationController
skip_before_filter :require_login, :only => [:new, :create]
end

