2012-01-02 53 views
3

我通過Rails教程第12章的工作,並獲得當用戶登出主頁/主頁上看到以下錯誤(登錄即可):NoMethodError在PagesController#家

我是新手Rails所以請在你的迴應中明確表示!非常感謝..

NoMethodError在PagesController#家

undefined method `feed' for nil:NilClass 

Rails.root:/用戶/ fkhalid2008 /文檔/先應用

應用程序跟蹤|框架跟蹤|全面跟蹤

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> 

回答

5

用戶未登入。因此,current_user方法返回nil,和紅寶石找不到feed方法。當用戶在簽訂

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

現在,新的崗位和源項目纔會檢索

+0

我該如何解決這個問題? – hikmatyar 2012-01-02 22:05:03

+0

我編輯了我的答案並添加了一個可能的解決方案 – alf 2012-01-02 22:07:45

+0

謝謝!它的工作:) – hikmatyar 2012-01-02 22:09:28

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