我查看过其他帖子,但我还不明白问题所在。我的show方法有问题吗?我正在按照教程进行操作,并将其留空。
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 %>
我的故事控制员:
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
端
错误:
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:
答案 0 :(得分:2)
class StoriesController < ApplicationController
before_action :find_story, only: [:destroy, :show, :edit, :update]
end # <--- this `end` breaks everything
您很快就会结束您的控制器定义。因此,它没有定义任何操作方法(这意味着没有@stories
)。
所有这些方法应该进入控制器,而不是坐在外面。