2016-07-25 101 views
0

我正在測試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 
+2

我建議退一步和研究MVC原則(谷歌它)。這個重定向應該放在控制器中,而不是放在視圖中。 –

回答

2

不知道你SessionsController看起來像什麼,而是你可以添加這樣的事情:

class SessionsController < ActionController::Base 
    before_action :check_current_user 

    def check_current_user 
    redirect_to :root, success: "You are already logged in." if current_user 
    end 
end 

然後你就可以在你的登錄視圖中刪除if current_user聲明。併爲您的登錄鏈接,你可以寫:

<%= link_to 'Login', new_session_path unless current_user %> 

這樣的登錄按鈕只顯示如果current_user是零。

此外,看一看Rails Tutorial Chapter 8: Basic Login瞭解更多信息

+0

不,我該如何做到這一點,以便當一個視圖呈現時,如果current_user不是零,它呈現另一個視圖? –

+0

您的問題中的視圖看起來像一個登錄頁面,而不是登錄部分。這是我的答案是基於。如果你想渲染一個登錄部分,我建議你採用Stephan L.的方法 –

1

在你的看法,你可以渲染渲染方法諧音,如果你只是想顯示的登錄按鈕,用戶是沒有登錄:

<% unless current_user %> 
    <%= render 'login_form' %> 
<% end %> 

然後,你需要有一個名爲「_login_form」文件在您的視圖目錄:

<%= form_for :session, url: '/login' do |s| %> 
<%= s.text_field :username, :placeholder => 'Username' %> 
<%= s.password_field :password, :placeholder => 'Password' %> 
<%= s.submit "Login" %>