我是 Rails 的新手,我一直在 stackoverflow 周围漫无目的地徘徊,试图找到解决问题的方法,但似乎无法弄清楚。我正在阅读 Michael Hartl 教程的第 10 章,当我尝试查看特定用户的个人资料时,localhost:3000 页面出现以下错误消息:
"NoMethodError in Users#show"
其次是
"undefined method `name' for nil:NilClass".
源代码列为我的 show.html.erb 文件的第一行,但我看不出代码有任何问题。
主页工作正常,用户索引可见,但除此之外它不起作用。我知道这可能意味着 @user 对象为零,但我不确定如何解决这个问题。我的 Rspec 测试也失败了 - 任何帮助将不胜感激。
我的 users_controller.rb 文件:
class UsersController < ApplicationController
before_filter :signed_in_user, only: [:index, :edit, :update, :destroy]
# Arranges for a particular method to be called before the given actions.
before_filter :correct_user, only: [:edit, :update]
before_filter :admin_user, only: :destroy # Restricts the destroy action to admins.
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
sign_in @user
flash[:success] = "Welcome to the Sample App!"
redirect_to @user
else
render 'new'
end
end
def index
@users = User.paginate(page: params[:page])
end
def edit
# @user = User.find(params[:id])
end
def update
# @user = User.find(params[:id])
if @user.update_attributes(params[:user])
flash[:success] = "Profile updated"
sign_in @user
redirect_to @user
else
render 'edit'
end
end
def destroy
User.find(params[:id]).destroy
flash[:success] = "User destroyed."
redirect_to users_url
end
private
# def signed_in_user
# unless signed_in?
# store_location
# redirect_to signin_url, notice: "Please sign in."
# end
# end
def correct_user
@user = User.find(params[:id])
redirect_to(root_path) unless current_user?(@user)
end
def admin_user
redirect_to(root_path) unless current_user.admin?
end
def show
@user = User.find(params[:id])
@microposts = @user.microposts.paginate(page: params[:page])
end
end
我的 show.html.erb 文件:
<% provide(:title, @user.name) %>
<div class="row">
<aside class="span4">
<section>
<h1>
<%= gravatar_for @user %>
<%= @user.name %>
</h1>
</section>
</aside>
<div class="span8">
<% if @user.microposts.any? %>
<h3>Microposts (<%= @user.microposts.count %>)</h3>
<ol class="microposts">
<%= render @microposts %>
</ol>
<%= will_paginate @microposts %>
<% end %>
</div>
</div>
和 users_helper.rb
module UsersHelper
# Returns the Gravatar (http://gravatar.com/) for the given user.
def gravatar_for(user, options = { size: 50 })
gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
size = options[:size]
gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}"
image_tag(gravatar_url, alt: user.name, class: "gravatar")
end
end