2013-01-08 9 views
0

레일스에 익숙하지 않은 나는 내 문제에 대한 해결책을 찾기 위해 노력하고 있지만, 알아낼 수없는 것처럼 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 
+0

왜 컨트롤러에서 표시 작업을 개인 메서드로 사용합니까? – Khaled

+0

감사합니다. Khaled! 내가 쇼 동작을 왜 여기에 넣었는지 모르겠다. 어리 석다. 나는 시퀀스의 끝에 그것을 추가했다. 그냥 개인적인 방법 밖으로 이동하고 지금은 테스트가 너무 감사 힙을 전달하고 있습니다! 휴 ... 이걸로 고통스러워 ... – user1884204

답변

0
여기

@user는 무기 호입니다. id (params [: id])가있는 레코드가 없기 때문입니다. 그게 왜이 오류가 올지.

@user = User.find(params[:id]) 

분명히 nil를 반환 않습니다

<h1> 
<%= gravatar_for @user %> 
<%= [email protected]? @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

또는 그는 [andand] (https://github.com/raganwald/andand) gem을 사용할 수 있습니다. – Hauleth

+0

그레이트 룰렛. 우리는 이것을 사용할 수 있습니다. 그리고 – vijikumar

+1

@vijikumar :'NoMethodError'는 여러 곳에서 발생하며 수정 사항은 그 중 하나만 사용하면 도움이됩니다. – Koraktor

0

귀하의 질의는 사용자를 찾을 수 없습니다.

해당 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 %> 
+0

사용자 색인을 통해 사용자 프로필 페이지로 이동하므로 기존 사용자를 클릭하십시오. 쿼리에서 사용자를 찾지 못하면 기존 사용자에게 어떻게 알릴 수 있습니까? – user1884204

+0

모든 답변에 대해 감사합니다. 그냥 바보 같은 실수 야. 해결! – user1884204