简体   繁体   English

如果我的用户已登录,如何包含其他文件?

[英]How do I include a different file if my user is logged in?

I'm using Rails 4.2.5. 我正在使用Rails 4.2.5。 I have this line in my “app/views/layouts/application.html.erb” file … 我的“ app / views / layouts / application.html.erb”文件中有这一行…

<%= yield %>

If the user is logged in, I would like to display the content from the page “./app/views/user_objects/index.html.erb” but if they are not, I would like to display content from the page “app/views/pages/_welcome.html.erb”. 如果用户已登录,我想显示页面“ ./app/views/user_objects/index.html.erb”中的内容,但如果不是,则想显示页面“ app / views / pages / _welcome.html.erb”。 I don't know how to set this up. 我不知道该如何设置。 In my config/routes.rb file I have 在我的config / routes.rb文件中

constraints lambda { |req| !req.session[:user_id].blank? } do
  root :to => 'user_objects#index', as: "dashboard"
end

root to: 'pages#index'

but that is displaying the “./app/views/user_objects/index.html.erb” file at all times, even if the user is not logged in. What do I need to add (or remove) to allow me to display the normal welcome page content if the user is not logged in? 但是即使用户未登录,该文件始终显示“ ./app/views/user_objects/index.html.erb”文件。我需要添加(或删除)哪些内容才能显示正常的欢迎页面内容(如果用户未登录)?

I'd do this a bit different. 我会做一些不同的事情。 In my config/routes.rb I'd have just the usual 在我的config / routes.rb文件中

root 'pages#index'

and then I'd change my index method at app/controllers/pages_controller.rb to 然后将app / controllers / pages_controller.rb的 索引方法更改为

def index
  if logged_user? 
    render 'user_objects/index'
  end
end

and then I'd put all this logic to say if the user is logged in a logged_user? 然后我会用所有这些逻辑来说明用户是否登录在logging_user中? method like 类似的方法

def logged_user?
  !session[:user_id].blank?
end

There are other ways to to this, of course. 当然,还有其他方法可以做到这一点。 But always keep the KISS Principle in mind. 但请始终牢记KISS原则

If you really want to understand all the rendering process, it would be better to give some attention to http://guides.rubyonrails.org/layouts_and_rendering.html 如果您真的想了解所有渲染过程,最好注意一下http://guides.rubyonrails.org/layouts_and_rendering.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM