[英]How to set a home page for logged in users and non logged in users?
How would I set in my rails app so that if a first time user comes to my site www.example.com they see a page that they can sign in but if an already logged in goes to www.example.com it now displays their own posts but still at the same www.example.com url. 我将如何在Rails应用程序中进行设置,以便如果首次访问我的网站www.example.com的用户看到的页面可以登录,但是如果已经登录www.example.com的用户现在可以显示其登录信息,拥有自己的帖子,但仍使用相同的www.example.com网址。
Would I do something like render template based if they are logged in or is there some other way to do this? 如果他们已登录,或者是否有其他方法可以执行基于渲染模板的操作?
You can set the users#home to be the root URL: 您可以将users#home设置为根URL:
def home
if logged_in?
@blogs = current_user.blogs
render :action => 'logged_in'
else
render :action => 'non_logged_in'
end
end
Have 2 files in the app/views/users folder: logged_in.html.erb & non_logged_in.html.erb app / views / users文件夹中有2个文件:logging_in.html.erb和non_logged_in.html.erb
A great article was writen by Steve Richert. 史蒂夫·里奇特(Steve Richert)写了一篇很棒的文章。 He is using advanced constraint when defining the route, see here 他在定义路线时使用了高级约束 , 请参见此处
It depends on how you are making your log in logic 这取决于您如何进行登录逻辑
Usually you should have two actions, one for home/login form and another for user logged in home. 通常,您应该执行两个操作,一个用于家庭/登录表单,另一个用于用户在家登录。 You can make a before_filter on your application controller, so you can test if the user is logged in or not and then redirect him to home (logged out) if not. 您可以在应用程序控制器上创建一个before_filter ,以便可以测试用户是否已登录,然后将其重定向到家(注销)。
If you are not using your own code or another solution I would like to recommend you this gem called devise , it implements a lot of login logic itself and is easy to change too. 如果您不使用自己的代码或其他解决方案,我想向您推荐这个叫做devise的 gem,它本身实现了很多登录逻辑,并且也很容易更改。
EDIT: I think this solutions is better than the others that were presented and I didn't put the code (although it is quite the same code of the before_filter link), so here it is: 编辑:我认为此解决方案比提出的其他解决方案要好,我没有放置代码(尽管它与before_filter链接的代码完全相同),所以这里是:
class ApplicationController < ActionController::Base
before_filter :require_login
private
def require_login
unless logged_in?
flash[:error] = "You must be logged in to access this section"
render :controller => 'home', :action => 'not_logged_in'
else
# whatever code you need to load from user
render :controller => 'home', :action => 'logged_in'
end
end
end
This solutions works perfectly because it tests if the user is logged in in every controller/action he tries to access. 该解决方案非常有效,因为它可以测试用户是否在他尝试访问的每个控制器/操作中登录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.