0

我正在尝试扩展 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(大概user.emailgravatar_for辅助方法使用的。

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

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

应用程序/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 %>

应用程序/视图/共享/_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>
4

1 回答 1

0

If gravatar_for calls email on the user you pass to it, then the error message is telling you that feed_item.user is nil.

Try putting <% raise feed_item.user %> the line before the link_to, and see if it is indeed nil. Also, a stack trace of the error is one of the most useful things you can put in a SO question.

于 2013-07-26T22:19:27.683 回答