我正在測試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原則(谷歌它)。這個重定向應該放在控制器中,而不是放在視圖中。 –