错误 - 未定义的方法`每个'为nil:NilClass

时间:2016-05-02 00:08:07

标签: ruby-on-rails

我收到错误undefined method每个'为nil:NilClass`

我已经阅读了有关它的帖子,但我仍然无法弄清楚出了什么问题。

这是我的控制器:

class BlogsController < ApplicationController

  def new
    @blog = Blog.new
  end

  def create
    @blog = Blog.new(blog_params)

    if @blog.save
      redirect_to @blog
    else
      render 'new'
    end
  end

  def show
    @blog = Blog.find(params[:id])
  end

  def edit
  end

  def destroy
  end

  def index

  end

  private

    def blog_params
      params.require(:blog).permit(:title, :body, :image)
    end

end

我对index.html.erb的看法:

<html>
  <head>

  </head>
  <body>
    <% @blogs.each do |blog| %>
    <h3><%= @post.title %></h3>
    <div><%= @post.body %></div>
    <% end %>
  </body>
</html>

对于nil:NilClass`

,完整错误为undefined method每个'

2 个答案:

答案 0 :(得分:2)

您的index方法什么都不返回。它应该是这样的:

  def index
    @blogs = Blog.all
  end

答案 1 :(得分:0)

@post未定义。您应该输出blog对象:

<html>
  <head>
  </head>
  <body>
    <% @blogs.each do |blog| %>
    <h3><%= blog.title %></h3>
    <div><%= blog.body %></div>
    <% end %>
  </body>
</html>
相关问题