【发布时间】:2015-02-19 08:38:46
【问题描述】:
当我尝试向我的网站添加简单的博客功能时,无法弄清楚发生了什么。我正在使用的 Starter 应用程序已针对 HAML 进行了预配置,而且我的 HAML n00b 比 Rails n00b 还要大,所以我很苦恼。
当我将它添加到我的 pages/home.html.haml 时:
%h1= I18n.t('brand.name')
%p
= I18n.t 'brand.name'
- @posts. each do |post|
= render 'posts/post', post: post
我明白了:
undefined method `each' for nil:NilClass
我想不通...我认为 Ruby 有一个“每个”方法构建它?为什么不传入任何类?
这是它试图渲染的 _post.html.haml 部分:
%p
%h2
= link_to post.title, post
%p
- if post.kind == 'image'
= image_tag post.content, style: "width: 100%"
- else
= simple_format post.content
%p.text-muted
%small
Posted on #{post.created_at.to_formatted_s(:long)}
还有控制器:
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
def index
@posts = Post.all
end
def show
@post = Post.find(params[:id])
end
def new
@post = Post.new
end
def edit
end
def create
@post = Post.new(post_params)
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
else
format.html { render action: 'new' }
end
end
end
def update
respond_to do |format|
if @post.update(post_params)
format.html { redirect_to @post, notice: 'Post was successfully updated.' }
else
format.html { render action: 'edit' }
end
end
end
def destroy
@post.destroy
respond_to do |format|
format.html { redirect_to posts_url }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_post
@post = Post.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def post_params
params.require(:post).permit(:title, :kind, :content)
end
end
而模型是空的,只是:
class Post < ActiveRecord::Base
end
我从我在教程中构建的一个工作博客示例中复制/粘贴了大部分代码,它在该应用程序中运行良好。
我怀疑它与 PSQL(在此应用程序中)与 SQLite(在示例应用程序中)有关。在 Rails 控制台中,尝试它会给出相同的错误:
[3] pry(main)> post = post.first
NoMethodError: undefined method `first' for nil:NilClass
[4] pry(main)> posts = post.each
NoMethodError: undefined method `each' for nil:NilClass
[5] pry(main)> posts = Post.each
NoMethodError: undefined method `each' for Post (call 'Post.connection' to establish a connection):Class
from /Users/troot/.rvm/gems/ruby-2.1.3/gems/activerecord-4.1.6/lib/active_record/dynamic_matchers.rb:26:in `method_missing'
我不明白为什么我认为应该有效的方法在这里不起作用。非常感谢您提供的任何帮助。
【问题讨论】:
标签: ruby-on-rails postgresql methods haml