我是Rails的新手,我一直在漫无目的地围绕stackoverflow徘徊,试图找到解决我的问题的方法,但似乎无法弄明白。我正在做Michael Hartl教程的第10章,当我尝试查看特定用户的配置文件localhost:3000页面时,我收到以下错误消息:
"NoMethodError in Users#show"
接着是
"undefined method `name' for nil:NilClass".
源代码列为show.html.erb文件的第一行,但我看不出代码有什么问题。
主页工作正常,用户索引是可见的,但除此之外它不起作用。我知道这可能意味着@user对象是nil,但我不知道如何解决这个问题。我的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
答案 0 :(得分:0)
@user是零。因为没有id的记录(params [:id])。这就是为什么会出现这个错误。
<h1>
<%= gravatar_for @user %>
<%= !@user.nil? @user.name : "" %>
</h1>
It will check whether the @user having any record, if its having it will display it's name else it will display empty.
答案 1 :(得分:0)
您的查询找不到用户:
@user = User.find(params[:id])
显然会返回nil
。
请检查具有给定ID的用户是否存在。此外,如果没有找到任何对象,您应该安全地失败:
<% if @user.nil? %>
<% provide(:title, 'Not found') %>
No user with that ID has been found.
<% else %>
<!-- Contents of your current show.html.erb -->
<% end %>