2015-11-01 21 views
0

我如何使它所以當登錄按鈕,用戶登錄改變他們的電子郵件中的導航欄更改日誌中的按鈕,用戶名紅寶石

class SessionsController < ApplicationController 

def new 
end 

def create 
    @guestaccount = Guestaccount.find_by_email(params[:session][:email]) 
    if @guestaccount && @guestaccount.authenticate(params[:session][:password]) 
    session[:guestaccount_id] = @guestaccount.id 
redirect_to '/guest?' 
else 
flash.now[:danger] = "Invalid email/password combination" 
    render 'new' 
end 
end 

def destroy 
    session[:guestaccount_id] = nil 
    redirect_to '/guest?' 
end 
end 

這是我的導航欄

<%= button_to "Returning Guest ", guestlogin_path, :method => "get", class: "button round success" %> 

回答

1
<% if session[:guestaccount_id] %> 
    <%= Guestaccount.find(session[:guestaccount_id]).email %> 
<% else %> 
    <%= button_to "Returning Guest ", guestlogin_path, :method => "get", class: "button round success" %> 
<% end %> 

會這樣做。隨意調整if/else塊內的樣式和內容。如果你有一個current_user,current_guestaccount或類似的方法,我會用它來代替會話和.find調用。

您可以在ApplicationController定義current_guestaccount方法:

class ApplicationController < ... 

    # Use this before internal/non-request (index/show/create/etc) controller methods 
    protected 

    # Usable in your controllers. E.g. authentication, loading associated data. 
    def current_guestaccount 
    # Return nil if the session value isn't set, don't query the DB 
    return nil unless session[:guestaccount_id] 
    # @x ||= y 
    # will make y run only once if it returns a successful value, 
    # essentially caching it for the entire request 
    @current_guestaccount ||= Guestaccount.find(session[:guestaccount_id]) 
    end 
    # This makes current_guestaccount, a controller method, accessible in your views. 
    helper_method :current_guestaccount 
end 

那麼在您看來,您可以使用

<% if current_guestaccount %> 
    <%= current_guestaccount.email %> 
<% else %> 
    <%= button_to "Returning Guest ", guestlogin_path, :method => "get", class: "button round success" %> 
<% end %> 

將使用1個SELECT查詢整個請求而不是多個。您還可以在視圖中使用類和HTML節點:

<% if current_guestaccount %> 
    <span class="guest-email"><%= current_guestaccount.email %></span> 
<% else %> 
    <%= button_to "Returning Guest ", guestlogin_path, :method => "get", class: "button round success" %> 
<% end %> 

稍後用CSS調整樣式。

+0

因此如果我沒有current_guestaccount會發生什麼,因爲那不會工作。因爲上面的方法可行,但是我的導航工具的使用方式讓我編輯它上面的按鈕 –

1

什麼本傑明·曼恩說,但是請不要把ORM查詢視圖模板類似...

如果用戶登錄的用戶應該存儲在控制器中。

<% if current_user %> 
    <%= current_user.email %> 
<% else %> 
    <%= button_to "Returning Guest ", guestlogin_path, :method => "get", class: "button round success" %> 
<% end>