레일스에 익숙하지 않은 나는 내 문제에 대한 해결책을 찾기 위해 노력하고 있지만, 알아낼 수없는 것처럼 stackoverflow 주위를 아무렇게나 돌아 다니고있다. 나는 마이클 하틀의 튜토리얼의 10 장을하고있어 나는 특정 사용자의 프로필 로컬 호스트 보려고 할 때 :레일즈 : NoMethodError in users # show
"NoMethodError in Users#show"
"undefined method `name' for nil:NilClass".
다음 : 나는 다음과 같은 오류 메시지가 얻을 3000 페이지 소스는 내 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
왜 컨트롤러에서 표시 작업을 개인 메서드로 사용합니까? – Khaled
감사합니다. Khaled! 내가 쇼 동작을 왜 여기에 넣었는지 모르겠다. 어리 석다. 나는 시퀀스의 끝에 그것을 추가했다. 그냥 개인적인 방법 밖으로 이동하고 지금은 테스트가 너무 감사 힙을 전달하고 있습니다! 휴 ... 이걸로 고통스러워 ... – user1884204