CH。 10.3.3 Ruby on Rails教程未定义的方法'any?'

时间:2013-06-17 20:10:07

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

我正在尝试在用户登录时在首页上放置所有待办事项的Feed。但是,即使Feed正在运行,@ feed_items也不会返回任何内容。 这是错误:

  

未定义的方法`any?'为零:NilClass

这是提取的来源:

1: <% if @feed_items.any? %>
2:  <ol class="todos">
3:      <%= render partial: 'shared/feed_item', collection: @feed_items %>
4:  </ol>

这是我的静态页面控制器:

class StaticPagesController < ApplicationController

def home
    if signed_in?
        @todo = current_user.todos.build
        @feed_items = current_user.feed.paginate(page: params[:page])
    end
end
end

这是我的User.rb

class User < ActiveRecord::Base
attr_accessible :email, :username, :password, :password_confirmation
has_secure_password

before_save { |user| user.email = email.downcase }
before_save :create_remember_token

has_many :todos, :dependent => :destroy

validates :username, :presence => true, length: { maximum: 50 }
validates :password, :presence => true, length: { minimum: 6 }
validates :password_confirmation, presence: true
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, :presence => true, 
        format: { with: VALID_EMAIL_REGEX },
        uniqueness: { case_sensitive: false }

def feed
  # This is preliminary. See "Following users" for the full implementation.
  Todo.where("user_id = ?", id)
end

private

def create_remember_token
  self.remember_token = SecureRandom.urlsafe_base64
end
end

这是我的主页(index.html.erb)

% if signed_in? %>
<div class="row">
    <aside class="span4">
        <section>
            <%= render 'shared/user_info' %>
        </section>
    </aside>
    <div class="span8">
        <h3>Todo Feed</h3>
        <%= render 'shared/feed' %>
    </div>
</div>
<% else %>
<div class="center hero-unit">
    <h1>Welcome to the To Do app!</h1>

    <p>This app allows people to create a to do list for themselves on the web  browser! HELLLZZZ YEEAAAHHH!!!</p>

    <%= link_to "Sign Up Here!", signup_path, class: "btn btn-large btn-primary" %>
    <%= link_to "Find your Friends (and other Users) Here!", users_path, class: "btn btn-large btn-primary" %>

提前非常感谢你!

4 个答案:

答案 0 :(得分:6)

Nil未提供方法any?。快速破解就是使用try方法:

<% if @feed_items.try(:any?) %>

答案 1 :(得分:3)

@feed_items为零,您正在尝试拨打any?Nil没有这种方法。

您的控制器是&#34; home&#34;,但您的视图是&#34; index&#34;。可能是您的控制器操作未被​​运行,并且@feed_items未被填充作为结果。尝试将home重命名为index,看看是否可以修复它。

答案 2 :(得分:1)

在创建操作中渲染'static_pages / home'之前,确保MicropostsController存在@feed_items = []

答案 3 :(得分:1)

参见Hartl Rails教程中的清单11.48。您需要将以下代码行添加到'todos'控制器中的'create'方法:@feed_items = []。在添加此行之前,我遇到了同样的问题。现在一切正常。