StaticPages#Home中的NoMethodError(未定义的方法'email'代表nil:NilClass

时间:2013-07-26 21:14:19

标签: ruby-on-rails railstutorial.org

我试图扩展Rails Tutorial Sample App以包含回复。

我创建了一个包含user_id的收件人模型,用于指定回复邮件的人和micropost_id

我在用户模型中添加了以下内容。

class User < ActiveRecord::Base
  ...
  has_many :replies, foreign_key: "user_id", class_name: "Recipient", dependent: :destroy
  has_many :received_replies, through: :replies, source: :micropost
  ...
  def feed
    Micropost.from_followed_by_and_replying_to(self)
  end
  ...
end

这是我的Micropost模型:

class Micropost < ActiveRecord::Base
  belongs_to :user
  ...
  has_many :recipients, dependent: :destroy
  has_many :replied_users, through: :recipients, :source => "user"
  ...
  def self.from_followed_by_and_replying_to(user)
    followed_ids = "SELECT followed_id FROM relationships
                    WHERE followed_id = :user_id"
    replier_ids  = "SELECT micropost_id FROM recipients
                    WHERE user_id = :user_id"
    where("user_id in (#{followed_ids}) 
           OR id in (#{replier_ids}) OR user_id = :user_id", 
           user_id: user.id)
  end
  ...
end

StaticPages #home动作加载Feed:

class StaticPagesController < ApplicationController
  def home
    if signed_in?
      @micropost  = current_user.microposts.build
      @feed_items = current_user.feed.paginate(page: params[:page])
    end
  end
  ...
end

然后,当登录并访问主页时,我会在此行获得NoMethodError in StaticPages#Home部分共享feed_item部分(app / views / shared / _feed_item.html.erb):

 <%= link_to gravatar_for(feed_item.user), feed_item.user %>

undefined method 'email' for nil:NilClass(大概来自user.email gravatar_for辅助方法使用的Micropost.from_followed_by_and_replying_to([some user])

当我在rails控制台中调用<% if signed_in? %> ... <%= render 'shared/user_info' %> <%= render 'shared/stats' %> <%= render 'shared/micropost_form' %> <%= render 'shared/feed' %> ... <% else %> ... <% end %> 时,从跟随的用户和回复中返回微博都没有问题,因此我不认为我的数据库查询不正确。感谢任何帮助,我真的很难过。

编辑:(从中删除了一些HTML)

应用程序/视图/ static_pages / home.html.erb:

<% if @feed_items.any? %>
  <%= render partial: 'shared/feed_item', collection: @feed_items %>
  <%= will_paginate @feed_items %>
<% end %>

应用程序/视图/共享/ _feed.html.erb:

<li id="<%= feed_item.id %>">
<%= link_to gravatar_for(feed_item.user), feed_item.user %>
    <%= link_to feed_item.user.name, feed_item.user %>
...
</li>

应用程序/视图/共享/ _feed_items.html.erb:

{{1}}

1 个答案:

答案 0 :(得分:0)

如果gravatar_for对您传递给它的用户调用email,则会显示错误消息,告知您feed_item.usernil

尝试将<% raise feed_item.user %>放在link_to之前,看看它是否确实nil。此外,错误的堆栈跟踪是您可以在SO问题中提出的最有用的事情之一。