我正在编写 RailsGuides 教程(创建博客应用程序)。当我运行服务器并打开时:/posts/new
一切看起来都很好。但是,当我尝试创建帖子时,出现此错误:
帖子中的 NoMethodError#show
显示 /home/darek/rails_projects/blog/app/views/posts/show.html.erb 其中第 3 行提出:
nil:NilClass 的未定义方法“标题”
提取的源代码(在第 3 行附近):
1 <p>
2 <strong>Title:</strong>
3 <%= @post.title %>
4 </p>
5 <p>
实际上帖子已创建,我可以在 /posts 看到标题和内容但是当我尝试使用显示特定帖子时,我得到了这个错误。我的第一个线索是换线
<%= @post.title %>
至
<%= @post.try(:title) %>
错误消失了,但问题没有解决。
当我尝试显示特定帖子时,我得到标题,而文本表单为空。这不是我想看到的;)
好的,这是代码
显示.html.erb
<p>
<strong>Title:</strong>
<%= @post.title %>
</p>
<p>
<strong>Text:</strong>
<%= @post.text %>
</p>
<h2>Add a comment:</h2>
<%= form_for([@post, @post.comments.build]) do |f| %>
<p>
<%= f.label :commenter %><br />
<%= f.text_field :commenter %>
</p>
<p>
<%= f.label :body %><br />
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<%= link_to 'Edit Post', edit_post_path(@post) %> |
<%= link_to 'Back to Posts', posts_path %>
Posts_controller.rb
class PostsController < ApplicationController
def new
@post = Post.new
end
def index
@posts = Post.all
end
def create
@post = Post.new(params[:post].permit(:title, :text))
if @post.save
redirect_to @post
else
render 'new'
end
end
private
def post_params
params.require(:post).permit(:title, :text)
end
def show
@post = Post.find(params[:id])
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update(params[:post].permit(:title, :text))
redirect_to @post
else
render 'edit'
end
end
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to posts_path
end
end
耙路线:
-VirtualBox:~/rails_projects/blog$ rake routes
Prefix Verb URI Pattern Controller#Action
post_comments GET /posts/:post_id/comments(.:format) comments#index
POST /posts/:post_id/comments(.:format) comments#create
new_post_comment GET /posts/:post_id/comments/new(.:format) comments#new
edit_post_comment GET /posts/:post_id/comments/:id/edit(.:format) comments#edit
post_comment GET /posts/:post_id/comments/:id(.:format) comments#show
PATCH /posts/:post_id/comments/:id(.:format) comments#update
PUT /posts/:post_id/comments/:id(.:format) comments#update
DELETE /posts/:post_id/comments/:id(.:format) comments#destroy
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
root GET / welcome#index
GET /posts/:id(.:format) posts#view
DELETE /posts/:id(.:format) posts#destroy
感谢您的帮助和兴趣!