Я знаю, что это распространенная ошибка и может быть решена путем проведения исследования (которое я сделал), однако, я просто не могу понять, почему мое приложение ломается, когда мой код похоже, все в порядке. Я надеюсь, что некоторые дополнительные глаза могут заставить меня пройти мимо этого.Ruby on Rails: NoMethodError in Users # show
Ошибки я получаю NoMethodError in Users#show
undefined 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
Вы действительно должны иметь трассировку стека с номерами строк. Это в вашей производственной среде? Если нет, попробуйте камень «лучше ошибок». Это может сэкономить массу вреда, предоставив вам более приятную страницу с REPL. –
Возможно, метод set_user не находит пользователя. Вы уверены, что ваш param 'id' верен? – rhernando