如何在嵌套评论中找到缺少的必需键:[:post_id]?

How to get to missing required keys: [:post_id] in nested comments?

我有群组展示页面,上面应该有帖子及其相应的评论。我的模型是:

class Group < ActiveRecord::Base
belongs_to :user
has_many :posts

class Post < ActiveRecord::Base
belongs_to :group
belongs_to :user
has_many :comments

class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post

在我看来,我在 group/show 页面上显示所有内容,因此我只使用创建和销毁 post 和评论的路由:

resources :groups
resources :posts, only: [:create, :destroy] do
 resources :comments, only: [:create, :destroy]
end

我的控制器看起来像:

class GroupsController < ApplicationController
def show
 @group = Group.find(params[:id])
 @posts = @group.posts.paginate(page: params[:page])
 @post = current_user.posts.build if user_signed_in?
 @comment = current_user.comments.build if user_signed_in?
end

class PostsController < ApplicationController
def create
 @post = current_user.posts.build(post_params)
 @group = Group.find(params[:group_id])
 if @post.save
   @group.posts << @post
   flash[:success] = "Post created!"
   redirect_to group_path(@group)
 else
   @posts = @group.posts.paginate(page: params[:page])
   @users = @group.users
   render 'groups/show'
 end
end

class CommentsController < ApplicationController
def create
 @comment = current_user.comments.build(comment_params)
 @post = Post.find(params[:post_id])
 @group = Group.find(params[:group_id])
 if @comment.save
  @post.comments << @comment
  flash[:success] = "comment created!"
  redirect_to group_path(@group)
 else
  @posts = @group.posts.paginate(page: params[:page])
  @users = @group.users
  render 'groups/show'
 end
end

在 group/show 页面上,我想要组描述和 post 的列表以及他们的评论。没有评论一切正常。但是在创建评论时,我无法处理如何识别我想要在其下创建此类评论的相应 post 的 post_id。我的评论表单如下所示:

<%= simple_form_for @comment, uri: post_comments_path do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= hidden_field_tag :post_id, @post.id %>
 <%= f.input :content,label: false, placeholder: "add comment", error: false %>
 <%= f.button :submit, "Comment", class: 'btn-primary' %>
<% end %>

唯一可访问的id是group_id,因为我使用它的显示页面,但如何到达post_id?

终于找到解决办法了。分解成零件后,我发现 post_id 在那里,但实际上 group_id 不见了。问题是创建评论时 post_id 和 group_id 都是必需的,但由于评论是嵌套的,我无法到达 group_id。解决方法很简单:

class CommentsController < ApplicationController
 def create
  @comment = current_user.comments.build(comment_params)
  @post = Post.find(params[:post_id])
  @group = @post.group