ruby-on-rails - channel 。 10.3.3 Ruby on Rails 教程未定义方法 'any?'

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

我试图在用户登录时将所有待办事项的提要放在首页上。但是,@feed_items 没有返回任何内容,即使提要正在运行。 这是错误:

undefined method `any?' for nil:NilClass

这是提取的源代码:

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

这是我的静态页面 Controller :

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

提前致谢!

最佳答案

Nil 没有提供方法any?。一个快速的 hack 是使用 try 方法:

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

关于ruby-on-rails - channel 。 10.3.3 Ruby on Rails 教程未定义方法 'any?',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17155942/

相关文章:

ruby-on-rails - ActiveRecord 不知道时区?

javascript - Angular Material mdToast 导致 AngularJS 无限 $digest 循环

ruby-on-rails - Linux、Rails、Mono C#、No-SQL 设置

ruby-on-rails - 与docker-compose bundle 在一起可从头开始安装gem

ruby-on-rails-3 - 在 Rails Controller 中呈现和重新引发异常

sql - 为什么这个查询运行缓慢?

ruby-on-rails - Rails 3 自动 Assets 部署到 Amazon CloudFront?

ruby-on-rails - 找不到 ApplicationController 中定义的操作

ruby-on-rails - Rails : "This error occurred while loading the following files: bcrypt"

ruby-on-rails - 当您可以只使用 "="(来自 Hartl 的教程)时,为什么需要分配方法?