转到主页后获取未定义的方法错误

时间:2014-12-05 06:13:51

标签: ruby-on-rails instance-variables gravatar

我正在构建一个Rails应用程序,在该网站的标题中显示用户的图像。辅助方法如下:

应用/助手/ users_helper.rb

# Returns the Gravatar for the given user.
def gravatar_for(user)
  gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
  gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}"
  image_tag(gravatar_url, alt: user.name, class: "gravatar")
end

我遇到的问题是,当登录用户点击徽标链接转到主页时,我收到此错误:

undefined method `email' for nil:NilClass

我使用实例变量在标题中显示用户的重力数字。这是导航菜单中的代码:

应用/视图/布局/ _header.html.erb

<header class="site-header">
<div class="site-header-content">
    <div class="site-header-content__nav">
        <figure class="site-header-content__nav--logo">
            <%= link_to image_tag("global/logo.png", alt: "Lemur") %>
            <figcaption><%= link_to "Lemur",   root_path %></figcaption>
        </figure>
        <input type="checkbox" id="toggle" />
        <nav class="site-header-content__nav--menu">
            <label for="toggle" class="toggle" data-open="&#xf0c9;" data-close="&#xf00d;" onclick></label>
            <ul>
                <% if logged_in? %>
                    <li><%= link_to "Users", users_path %></li>
                    <li><%= link_to "Sign Out", logout_path, method: "delete" %></li>
                <% else %>
                    <li><%= link_to "About",   about_path %></li>
                    <li><%= link_to "Terms",   terms_path %></li>
                    <li><%= link_to "Help",   help_path %></li>
                    <li><%= link_to "Sign In", login_path %></li>
                <% end %>
            </ul>
        </nav>
    </div>
    <% if current_page?(root_path) && !logged_in? %>
        <div class="site-header-content__callout">
            <h1>Get the word out!</h1>
            <p>Write about what's happening around you, post about upcoming events and more with Lemur.</p>
            <div class="site-header-content__callout--buttons">
                <%= link_to "Sign Up", signup_path, class: "btn btn__lg btn__primary" %>
                <%= link_to "Sign In", login_path, class: "btn btn__lg btn__primary" %>
            </div>
        </div>
        <div class="site-header-content__down-arrow">
            <a href="#home-feature__local"><%= embedded_svg "down.svg" %></a>
        </div>
    <% end %>
</div>

我在这里做错了什么?

,我希望当用户仍然登录时,gravatar会显示在网站范围内

1 个答案:

答案 0 :(得分:0)

您提到过“当登录用户点击徽标链接转到主页时,我收到此错误:”

请检查root_path。在config / routes.rb中(我假设通过点击徽标,您将用户带到主页。)

例如:root 'home#index'

然后在HomeController中

def index
  @user = get the user
end