我正在用Rails制作一个简单的bbs,很抱歉用日语。我刚收到一条错误消息
"NoMethodError in Posts#new“ 显示第7行所显示的/Users/igarashinobuo/portfolio/cpmybbs/app/views/posts/new.html.erb: 零的未定义方法“`posts”:NilClass
当我想访问'http://localhost:3002/topics/22/posts/new‘时,会发生此错误。22个是员额的数目。新页面用于微信页面。
# app/views/posts/new.html.erb
<div class="text-center bg-light font-weight-normal pt-3">
<a href=/topics>Chatty</a>
</div>
<div class="text-center pb-20 mt-10">
</div>
<div class="mt-10 pd-20">
<% @topic.posts.order(:id).each.with_index(1) do |post , idx| %>
<p>
<%= idx %>
<%= post.name %>
<%= post.body %>
</p>
<% end %>
</div>
<div class="newpost my-auto mb-60">
<h4>新規書き込み</h4>
<%= form_for @post, url: topic_posts_path(@topic) do |f| %>
<div class="post_area">
<p><%= f.text_field :name %></p>
<p><%= f.label :name %></p>
<p><%= f.text_field :name %></p>
<p><%= f.label :body %></p>
<p><%= f.text_area :body %></p>
<%= f.submit %>
</div>
<% end %>
# posts_controller.rb
class PostsController < ApplicationController
def new
@post = Post.new
end
def create
@post = @topic.posts.build(set_topic)
if @post.save
redirect_to new_topic_post_path(@topic)
else
render :new
end
end
private
def set_topic
@topic = Topic.find(params[:topic_id, :title])
end
def post_params
params.require(:post).permit(:name, :body)
end
end
# error log
app/views/posts/new.html.erb:7:in `_app_views_posts_new_html_erb__4195515470978617912_70184702044840'
Started GET "/topics/22/posts/new" for ::1 at 2019-02-06 11:52:00 +0900
Processing by PostsController#new as HTML
Parameters: {"topic_id"=>"22"}
Rendering posts/new.html.erb within layouts/application
Rendered posts/new.html.erb within layouts/application (3.3ms)
Completed 500 Internal Server Error in 11ms (ActiveRecord: 0.0ms)
ActionView::Template::Error (undefined method `posts' for nil:NilClass):
4: <div class="text-center pb-20 mt-10">
5: </div>
6: <div class="mt-10 pd-20">
7: <% @topic.posts.order(:id).each.with_index(1) do |post , idx| %>
8: <p>
9: <%= idx %>
10: <%= post.name %你能帮我调试一下吗?
发布于 2019-02-06 03:04:51
您需要向控制器添加一些更改:
set_topic,以查找每个操作的@topicset_topic,出于某些原因,您可以通过以下方式查找主题
params[:topic_id, :title],它是访问散列值的无效方式。post_params构建一个新的帖子结果:
class PostsController < ApplicationController
before_action :set_topic
def new
@post = Post.new
end
def create
@post = @topic.posts.build(post_params)
if @post.save
redirect_to new_topic_post_path(@topic)
else
render :new
end
end
private
def set_topic
@topic = Topic.find(params[:topic_id])
end
def post_params
params.require(:post).permit(:name, :body)
end
endhttps://stackoverflow.com/questions/54545990
复制相似问题