开发者

Ruby on Rails Error: The error occurred while evaluating nil.each

I'm trying to learn Ruby but I geep getting this error:

The error occurred while evaluating nil.each

I was reading here the "Getting started" guide http://guides.rubyonrails.org/getting_started.html

Here's a piece of code from index.html.erb:

<h1>Listing snippets</h1>
<div class="snippets">
<% @posts.each do |post| %>
    <h2><%= post.title %></h2>
    <p><%= link_to 'View', post %> | <%= link_to 'Edit', e开发者_如何学Pythondit_post_path(post) %> | <%= link_to 'Delete', post, :confirm => 'Are you sure?', :method => :delete %></p>
<% end %>
</div>

Now the @posts var in posts_controller.rb

def index
    @posts = Post.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @posts }
    end
  end

What am I doing wrong? Thanks.

PS: I see that they are displayed here http://127.0.0.1:3000/posts but what if I want to display them in the root folder (http://127.0.0.1:3000/)


You should make a partial and put that post logic inside of it.

Then you can put it on any view as long as you initialize the collection inside of each used controller action.

So in your home controller you'd still need:

@posts = Post.find(:all)

As far as your first question, try finding them via @posts = Post.find(:all)


Add a route to routes.rb (for Rails 2.x only):

map.root :controller => "posts", :action => "index"

For Rails 3.x have a look here: http://guides.rubyonrails.org/routing.html#using-root

The error occurred while evaluating nil.each means that @posts is not an Array. Have you created a posts table?


The error is (as you probably suspected) happening in the following line:

<% @posts.each do |post| %>

Somehow @posts ends up being nil, even though we want it to be a list.

That's a little weird, because the code above looks like it should work. I'll try to help you track down the problem.

Post.all is equivalent to Post.find(:all), and according to the documentation for find, it could return nil, but I don't know when this would ever happen in practice. Normally it should return an empty list ([]) if there are no posts in the database, or raise an exception if the database table doesn't exist at all.

So just in case Post.all somehow returns nil, try @posts = [] instead of @posts = Post.all in the controller. The .each should work then.

If (as I suspect), it doesn't, my guess is that somehow a different controller from the one you posted above gets executed. Then, because @posts has never been set, trying to access it will simply give you nil, which explains the error. So check your paths and class names, and make sure that the code you think gets run actually gets run.

Hope that helps you figure out what's going wrong -- and let us know what solved the problem for you!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜