【问题标题】:NoMethodError in StaticPages#Home (undefined method 'email' for nil:NilClassStaticPages#Home 中的 NoMethodError(nil:NilClass 的未定义方法“电子邮件”
【发布时间】:2013-07-26 21:14:19
【问题描述】:

我正在尝试扩展 Rails 教程示例应用程序以包含回复。

我创建了一个 Recipient 模型,其中包含一个 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 操作加载提要:

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(大概来自gravatar_for辅助方法使用的user.email

当我在 Rails 控制台中调用Micropost.from_followed_by_and_replying_to([some user]) 时,返回关注用户的微博和回复都没有问题,所以我不认为我的数据库查询在这里不正确。任何帮助表示赞赏,我真的很难过。

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

app/views/static_pages/home.html.erb:

<% if signed_in? %>
...
  <%= render 'shared/user_info' %>
  <%= render 'shared/stats' %>
  <%= render 'shared/micropost_form' %>
  <%= render 'shared/feed' %>
...
<% else %>
...
<% end %>

app/views/shared/_feed.html.erb:

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

app/views/shared/_feed_items.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>

【问题讨论】:

  • 你也可以发布你的home.html.erb吗?
  • 你的 Micropost 类中有 b​​elongs_to :user 吗?

标签: ruby-on-rails railstutorial.org


【解决方案1】:

如果gravatar_for 在您传递给它的用户上调用email,则错误消息告诉您feed_item.usernil

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-14
    • 2013-01-14
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多