2014-09-09 8 views
0

이것은 일반적인 오류이며 연구를 수행하여 해결할 수 있음을 알고 있습니다. 그러나 나는 왜 내 응용 프로그램이 내 코드를 위반하는지 알 수 없습니다. 모두 질서가있는 것 같습니다. 나는 여분의 눈이 나를 이길 수 있기를 바라고있다.Ruby on Rails : NoMethodError in users # show

내가 점점 오전 오류는 NoMethodError in Users#showundefined method [] 무기 호에 대한 : NilClass` 사전에

감사

모델 :

class User < ActiveRecord::Base 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable, :omniauthable 

     has_many :posts, dependent: :destroy 


    def self.find_or_create_from_auth_hash(auth_hash) 
    find_by_auth_hash(auth_hash) || create_from_auth_hash(auth_hash) 
    end 

    def self.find_by_auth_hash(auth_hash) 
    where(
     provider: auth_hash.provider, 
     uid:  auth_hash.uid 
     ).first 
    end 

    def self.create_from_auth_hash(auth_hash) 
    create(
     provider:   auth_hash.provider, 
     uid:    auth_hash.uid, 
     email:   auth_hash.info.email, 
     name:    auth_hash.info.name, 
     oauth_token:  auth_hash.credentials.token, 
     oauth_expires_at: Time.at(auth_hash.credentials.expires_at) 
     ) 
    end 

    def password_required? 
    super && provider.blank? 
    end 

    def update_with_password(params, *options) 
    if encrypted_password.blank? 
     update_attributes(params, *options) 
    else 
     super 
    end 
    end 

    def facebook 
    @facebook ||= Koala::Facebook::API.new(oauth_token) 
    end 

    def get_profile_info 
    self.facebook.get_object("me") 
    end 

    def get_location 
    h = get_profile_info["location"] 
    h ["name"] 
    end 

    def get_books 
    self.facebook.get_connection("me", "books") 
    end 

    def get_profile_picture 
    self.facebook.get_picture(uid) 
    end 

end 

보기 :

<div class="container"> 
    <div class="row"> 
     <div class="col-lg-4"> 
      <div class="media"> 
       <%= image_tag @user.get_profile_picture, class: "pull-left" %> 
       <div class="media-body"> 
        <h4 class="media-heading"><%= @user.name %></h4> 
        from <%= @user.get_location %> 
       </div> 
      </div> 
      <hr /> 
      <div class="books"> 
       <% @user.get_books.each do |book| %> 
       <p><%= book["name"] %></p> 
       <% end %> 
     </div></div> 

     <div class="col-lg-6"> 
      <% @users.posts.order("created_at DESC").each do |post| %> 

      <div class="post"> 

       <h5><%= post.title %></h5> 
       <p><%= post.content %></p> 

       <span class="pull-right label label-info"><%= time_ago_in_words(post.created_at) %> ago</span> 

       <% if post.user == current_user %> 
       <span class="pull-left"><%= link_to 'edit', edit_post_path(post), class: "btn btn-xs btn-primary" %> <%= link_to 'destroy', post, class: "btn btn-xs btn-danger", method: :delete, data: {confirm: 'Are you sure?'} %></span> 
       <% end %> 
      </div> 
      <% end %> 
     </div> 
    </div> 
</div> 

컨트롤러 :

class UsersController < ApplicationController 
    before_action :set_user, only: [:show] 
    def index 
     @users = User.all 
    end 

    def show 
    end 

    private 

    def set_user 
     @user = User.find(params[:id]) 
    end 
end 
+0

당신은 정말한다고 행 번호와 스택 추적을 할 수 있습니다. 프로덕션 환경에 있습니까? 그렇지 않다면, '더 나은 오류'보석을 사용해보십시오. 실제 REPL로 훨씬 멋진 오류 페이지를 제공하여 전체 상처를 줄일 수 있습니다. –

+0

아마도 set_user 메소드는 사용자를 찾지 않습니다. 당신의 param 'id'가 맞습니까? – rhernando

답변

1

나는 3 가지 후보를 간첩합니다.

<% @user.get_books.each do |book| %> 
    <p><%= book["name"] %></p> <!-- <-- here --> 
<% end %> 

액세스 된 페이스 북 데이터는 그 장소 중 하나 nil을 할 수있는보기

def get_location 
    h = get_profile_info["location"] # <-- here 
    h ["name"] # <-- here (most likely) 
end 

한 모델의

두.

1

Jesse 옳다고 생각하지만, 더 중요한 것은, 여러 가지 다른 문제는 당신은 당신의 show보기로 내가 감히 무엇을 제공 한


변수를 주장 할 수있다

여기서 문제는 두 인스턴스 변수를 호출한다는 것입니다.

<% @user.each ... %> 

<% @users.posts.order("created_at DESC").each do |post| %> 

[] 문제를 해결 한 후에는 정의되지 않은 변수 @users에 대한 참조가 발생합니다. 이 문제를 해결하려면, 당신은 당신의 컨트롤러에 @users 변수를 설정하거나 @user (만 세트 변수)


오류를 참조해야 하나

당신이 []하지에 지점을 게시 한 오류를 호출 한 다양한 데이터에 유효합니다.

Jesse

은 "수정"(하나가 배열 참조를 조건 적으로 만든다, 또는 당신이 그들을 백업 할 데이터를 가지고 있는지 확인하는 것입니다 IE (오류 가능성이 상주 할 곳으로) 올바른 참조를 만든 FB 데이터를 데이터베이스에 저장).

는 다음 조건을 결정하는 방법은 다음과 같습니다

#app/views/users/show.html.erb 
<% if @user.get_books.any? %> 
    <% @user.get_books.each do |book| %> 
     <%= book["name"] %> 
    <% end %> 
<% end %> 

<%= @user.get_location % if @user.get_location.any? %>