我完成了關於Michael Hartl的Rails Tutorial的chapter 8,所以我已經設置了應用程序來爲用戶登錄&登錄和註銷。如何在整個應用程序視圖中全局使用user_helper方法?
我想要做的是在application.html.erb(或更具體地說_header.html.erb部分內)中用戶User Helper方法。
我想使用gravatar_for方法(在user_helper.rb中定義)來顯示用戶的gravatar圖片和用戶名,而不是使用下拉式單詞「Account」。
module UsersHelper
# Returns the Gravatar for the given user.
def gravatar_for(user, options = { size: 150})
gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
size = options[:size]
gravatar_url = "http://gravatar.com/avatar/#{gravatar_id}?s=#{size}"
image_tag(gravatar_url, alt: user.name, class: "gravatar")
end
end
在show.html.erb頁面我有以下代碼
<% provide(:title, @user.name) %>
<div class="row">
<aside class="span6">
<section>
<h1>
<%= gravatar_for @user %>
<%= @user.name %>
</h1>
</section>
</aside>
</div>
這顯示他們的個人資料頁上的用戶的gravatar和名稱。所以我試圖做的是像這樣將這些相同的方法添加到標題部分;
<% if signed_in? %>
<li id="fat-menu" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<span id="small">
<%= gravatar_for @user %><%= @user.name %><b class="caret"></b>
</span>
</a>
<ul class="dropdown-menu">
<li><%= link_to "Profile", current_user %></li>
<li><%= link_to "Settings", '#' %></li>
<li class="divider"></li>
<li><%= link_to "Sign out", signout_path, method: "delete" %></li>
</ul>
</li>
<% else %>
<li id="cta"><%= link_to "+ Sign up", signup_path %></li>
<li><%= link_to "Sign in", signin_path %></li>
<% end %>
這代碼顯示了show.html.erb頁面,我假設在完全沒問題,因爲它的show動作的用戶控制器上。但是,當我嘗試點擊主頁或真的任何其他頁面外的用戶查看然後我得到的錯誤
NoMethodError in Pages#about
undefined method `email' for nil:NilClass
所以我想我的問題是我怎麼做的gravatar爲方法和@ user.name可用於全部整個應用程序的意見。我覺得答案應該相當簡單,但我對軌道很新,所以任何幫助將不勝感激!