我有群组展示页面应该是帖子及其相应的评论。我的模特是:
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
在我的视图中,我在组/节目页面上显示所有内容,因此我只使用创建和销毁帖子和评论的路线:
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
在小组/节目页面上我想要小组描述和帖子列表及其评论。没有评论一切正常。但是在创建评论时,我无法处理如何识别其相应帖子的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?
答案 0 :(得分:0)
终于找到了解决方案。在拆解到部件后,我发现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