PagesController #home中的NoMethodError

时间:2012-01-02 22:00:35

标签: ruby-on-rails railstutorial.org nomethoderror

我正在使用Rails教程第12章,当用户注销时(登录即可),在Home / Main页面上出现以下错误:

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

PagesController中的NoMethodError #home

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 %>

Feed Partial

<% 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 Partial

<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>

2 个答案:

答案 0 :(得分:5)

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

您可以将代码更改为:

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

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

答案 1 :(得分:0)

app / controllers / 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