0

我在第 9.4.3 节的末尾,在您登录和退出时更改了标题链接。当我尝试加载任何页面时,我收到相同的错误:

Showing C:/Sites/sample_app/app/views/layouts/_header.html.erb where line #7 raised:
undefined local variable or method `id' for #<Class:0x5cbd658>

Extracted source (around line #7):
4:  <nav class="round">
5:      <ul>
6:          <li><%= link_to "Home", root_path %></li>
7:          <% if signed_in? %>
8:              <li><%= link_to "Profile", current_user %></li>
9:          <% end %>
10:             <li><%= link_to "Help", help_path %></li>

模板包含的痕迹:app/views/layouts/application.html.erb

Rails.root: C:/Sites/sample_app 应用程序跟踪 | 框架跟踪 | 全跟踪

app/models/user.rb:47:in `authenticate_with_salt'
app/helpers/sessions_helper.rb:26:in `user_from_remember_token'
app/helpers/sessions_helper.rb:12:in `current_user'
app/helpers/sessions_helper.rb:16:in `signed_in?'
app/views/layouts/_header.html.erb:7:in `_app_views_layouts__header_html_erb__376347676_36919992'
app/views/layouts/application.html.erb:10:in `_app_views_layouts_application_html_erb___333215577_32850792'

这是我的 session_helper.rb 文件:

module SessionsHelper
def sign_in(user)
    cookies.permanent.signed[:remember_token] = [user.id, user.salt]
    current_user = user
end

def current_user=(user)
    @current_user = user
end

def current_user
    @current_user ||= user_from_remember_token
end

def signed_in?
    !current_user.nil?
end

def sign_out
    cookies.delete(:remember_token)
    current_user = nil
end

private
    def user_from_remember_token
        User.authenticate_with_salt(*remember_token)
    end

    def remember_token
        cookies.signed[:remember_token] || [nil, nil]
    end
end

我还用Github上的内容检查了我的代码,但我无法弄清楚我做错了什么。

4

1 回答 1

0

您可能只是犯了复制粘贴错误。您的第 46 行user.rb应为:

def self.authenticate_with_salt(id, cookie_salt)
  user = find_by_id(id)
  (user && user.salt == cookie_salt) ? user : nil
end

您使用的参数来自User.authenticate类方法。

(另外,请不要使用制表符,这是不好的 Ruby 风格。)

于 2011-11-14T22:29:27.660 回答