Benjamints Benjamints - 4 days ago 6
Ruby Question

NoMethodError in Stories#index, undefined method 'each'

I have looked over other posts but I have not understood what the problem is. Is there a problem with my show method? I am following a tutorial and he has left it blank.

Index.html.erb

<% page_header "Our cool stories" %>

<p><%= link_to 'Tell one!', new_story_path, class: 'btn btn-primary btn-large' %></p>

<% @stories.each do |stories| %>
<div class="well well-lg">
<h2><%= link_to story.title, story_path(story) %></h2>

<p><%= truncate(story.body, length: 350) %></p>

<div class="btn-group">
<%= link_to 'Edit', edit_story_path(story), class: 'btn btn-info' %>
<%= link_to 'Delete', story_path(story), data: {confirm: 'Are you sure?'}, method: :delete, class: 'btn btn-danger' %>
</div>
</div>
<% end %>


my stories controller:

class StoriesController < ApplicationController
before_action :find_story, only: [:destroy, :show, :edit, :update]
end

def index
@stories = Story.order('created_at DESC')
end

def new
@story = Story.new
end

def create
@story = Story.new(story_params)
if @story.save
flash[:success] = "Your beautiful story has been added!"
redirect_to root_path
else
render 'new'
end
end

def edit
end

def update
if @story.update.attributes(story_params)
flash[:success] = "More knowledge, more wisdom"
redirect_to root_path
else
render 'edit'
end
end

def destroy
if @story.destroy
flash[:success] = "I think you should have more confidence in your storytelling"
else
flash[:error] = "Can't delete this story, sorry"
end

def show
@stories = Story.all
end

private

def story_params
params.require(:story).permit(:title, :body)
end

def find_story
@story = Story.find(params[:id])
end


end

Error:

NoMethodError in Stories#index

Showing /home/benjamin/Desktop/oxygen/app/views/stories/index.html.erb where line #5 raised:

undefined method `each' for nil:NilClass

Extracted source (around line #5):


<p><%= link_to 'Tell one!', new_story_path, class: 'btn btn-primary btn-large' %></p>

<% @stories.each do |stories| %>
<div class="well well-lg">
<h2><%= link_to story.title, story_path(story) %></h2>

I also receive this error in my terminal:

ActionView::Template::Error (undefined method `each' for nil:NilClass):
2:
3: <p><%= link_to 'Tell one!', new_story_path, class: 'btn btn-primary btn-large' %></p>
4:
5: <% @stories.each do |stories| %>
6: <div class="well well-lg">
7: <h2><%= link_to story.title, story_path(story) %></h2>
8:

Answer
class StoriesController < ApplicationController
    before_action :find_story, only: [:destroy, :show, :edit, :update]
end  # <--- this `end` breaks everything 

You end your controller definition very soon. Therefore, it doesn't have any action methods defined (which means no @stories for you).

All those methods should go into controller, not sit outside.

Comments