我正在测试RoR,并且正在尝试弄清楚允许用户使用有效会话跳过登录的功能。如何使用条件渲染视图中的视图?
登录按钮通常会提示您登录页面,但我想使它以便会话的人跳过它并立即使用条件语句重定向到show view。 (通过CURRENT_USER检查) (如果您需要任何其他代码只是评论)
这里的登录视图
<%= form_for :session, url: '/login' do |s| %>
<%= s.text_field :username, :placeholder => 'Username' %>
<%= s.password_field :password, :placeholder => 'Password' %>
<%= s.submit "Login" %>
<% if current_user %>
<!-- What do i write here? -->
<!-- Maybe I should put this in a controller? -->
<% end %>
<% if flash[:notice] && current_user %>
<div class="notice"><%= flash[:notice] %></div>
<% end %>
下面是一个包含了CURRENT_USER功能的应用程序控制器。 (万一)
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
helper_method :current_user
def current_user
@current_user ||= User.find_by(id: session[:id]) if session[:id]
end
end
我建议退一步和研究MVC原则(谷歌它)。这个重定向应该放在控制器中,而不是放在视图中。 –