3

我正在阅读 Rails 教程第 12 章,当用户退出(登录正常)时,主页/主页上出现以下错误:

我是 Rails 的新手,所以请在您的回复中明确说明!非常感谢..

PagesController#home 中的 NoMethodError

undefined method `feed' for nil:NilClass

Rails.root:/Users/fkhalid2008/Documents/First-app

应用程序跟踪 | 框架跟踪 | 全跟踪

app/controllers/pages_controller.rb:6:in `home'

页面控制器

class PagesController < ApplicationController

def home
  @title = "Home"
  @post = Post.new if signed_in?
  @feed_items = current_user.feed.paginate(:page => params[:page])
end

def contact
  @title = "Contact"
end

def about
  @title = "About Us"
end

end

主页视图 (/app/views/pages/home.html.erb)

<% if signed_in? %>
<table class="front" summary="For signed-in users">
<tr>
  <td class="main">
    <h1 class="post">What's up?</h1>
    <%= render 'shared/post_form' %>
    <%= render 'shared/feed' %>
  </td>
  <td class="sidebar round">
    <%= render 'shared/user_info' %>
  </td>
</tr>
</table>
<% else %>
<h1>Palazzo Valencia</h1>

<p>
This is the home page for the
<a href="http://railstutorial.org/">Palazzo Valencia</a>
sample application.
</p>

<%= link_to "Sign up now!", signup_path, :class => "signup_button round" %>
<% end %>

饲料部分

<% unless @feed_items.empty? %>
<table class="posts" summary="User posts">
<%= render :partial => 'shared/feed_item', :collection => @feed_items %>
</table>
<%= will_paginate @feed_items %>
<% end %>

Feed_item 部分

<tr>
<td class="gravatar">
<%= link_to gravatar_for(feed_item.user), feed_item.user %>
</td>
<td class="post">
<span class="user">
  <%= link_to feed_item.user.name, feed_item.user %>
</span>
<span class="content"><%= feed_item.content %></span>
<span class="timestamp">
  Posted <%= time_ago_in_words(feed_item.created_at) %> ago.
</span>
</td>
<% if current_user?(feed_item.user) %>
<td>
<%= link_to "delete", feed_item, :method => :delete,
                                 :confirm => "You sure?",
                                 :title => feed_item.content %>
</td>
<% end %>
</tr>
4

2 回答 2

5

用户未登录。因此,该current_user方法返回 nil,而 ruby​​ 找不到该feed方法。

您可以将代码更改为:

@title = "Home"
if signed_in?
    @post = Post.new
    @feed_items = current_user.feed.paginate(:page => params[:page])
end

现在,只有在用户登录时才会检索新帖子和提要项目。

于 2012-01-02T22:03:17.167 回答
0

应用程序/控制器/static_pages_controller.rb

  def home
    if logged_in?
      @micropost  = current_user.microposts.build
      @feed_items = current_user.feed.paginate(page: params[:page])
    end
  end
于 2015-10-27T12:51:02.217 回答