ruby on rails——在一个基本的ROR博客应用程序中,似乎无法弄清楚帖子和评论的关系



所以当我尝试访问http://127.0.0.1:3000/users/1/posts/17时,我得到一个错误

undefined method `post_comments_path' for #<#<Class:0x007fece23212a8>:0x007fece2a7c110>
Extracted source (around line #1):
1: <%= form_for([@post, @comment]) do |f| %>
2: 
3:  <%= f.label :name %>
4:

这是引用到我的文件- /app/views/posts/_form_comment.html.erb where line #1 raised:

我的/app/views/posts/_form_comment.html.erb文件如下-

<%= form_for([@post, @comment]) do |f| %>
    <%= f.label :name %>
    <br />
    <%= f.text_field :name%>
    <br />
    <%= f.label :comment %>
    <br />
    <%= f.text_area :comment%>
    <br />
<%= f.submit "Create comment" %>
<% end %>

这里是我的PostController

中的show方法
def show
    @post = Post.find(params[:id])
    @comment = @post.comments.build
    @cl = Comment.where(:post_id => @comment[:post_id])
  end

现在请注意,如果清空文件/app/views/posts/_form_comment.html.erb的内容,页面将正常加载。显示文章标题和内容。除了评论部分。所以,我猜评论部分有问题。但我不知道。

重要提示:这种情况以前没有发生过。在我将用户模型与post模型相关联之前,它工作得很好。谢谢。

更新:我的路线看起来像-

  resources :users, only: [:show] do 
    resources :posts do
    end
    resources :comments, only: [:create]
  end

你应该有一个像

resources :posts do
  resources :comments
end

在你的路由。这是url_for[@post, @comment]成功创建路由所需要的

更新:包括嵌套的帖子和用户资源

resources :posts do
  resources :comments
end
resources :users do
  resources :posts
end

相关内容