<% 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調整樣式。
因此如果我沒有current_guestaccount會發生什麼,因爲那不會工作。因爲上面的方法可行,但是我的導航工具的使用方式讓我編輯它上面的按鈕 –