我正在使用ancestry gem在我的帖子中创建嵌套评论。
我使用Rails 5。
这是我的代码:
发布模型
has_many :comments
评论模型
has_ancestry
belongs_to :post
我在视图/帖子/节目中呈现所有评论
<%= render 'comment' %>
内部视图/评论/ _评论
<%= div_for(comment) do %>
<%= comment.body %>
<%= link_to "Reply", new_post_comment_path(:parent_id => comment, :post_id => @post.id) %>
<% end %>
comments_controller
def create
@comment = @post.comments.new(comment_params)
@comment.user = current_user
respond_to do |format|
if @comment.save
format.html { redirect_to @post, notice: 'Comment was successfully created.' }
format.json { render json: @comment, status: :created, location: @comment }
else
format.html { render action: "new" }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
def new
@comment = Comment.new(:parent_id => params[:parent_id])
end
评论表
<%= simple_form_for new_post_comment_path(@post,@comment) do |f| %>
<%= f.hidden_field :parent_id %>
<%= f.text_area :body, class: "form-control" %>
<%= f.submit "Leave Comment", class: 'btn btn-main btn-block' %>
<% end %>
Routes.rb
resources :posts do
resources :comments
end
耙路
post_comments GET /:post_id/comments(.:format) comments#index
POST /:post_id/comments(.:format) comments#create
new_post_comment GET /:post_id/comments/new(.:format) comments#new
edit_post_comment GET /:post_id/comments/:id/edit(.:format) comments#edit
post_comment GET /:post_id/comments/:id(.:format) comments#show
PATCH /:post_id/comments/:id(.:format) comments#update
PUT /:post_id/comments/:id(.:format) comments#update
DELETE /:post_id/comments/:id(.:format) comments#destroy
在此URL http://localhost:3000/post_id/comments/new?parent_id=10
中
,我点击了“回复评论”,它呈现了新的评论表格。
但是,如果我单击“提交”按钮,则会出现此错误
没有路线匹配[POST]“ / post_id / comments / new”
请有人帮我解决。谢谢
答案 0 :(得分:0)
忘记我的评论。我混合了一些东西。
您的问题在
评论, :post_id => @ post.id)%>
new_post_comment_path
解析为/:post_id/comments/new(.:format) comments#new
,由于其GET路径并且没有POST,因此它不起作用。
您必须发布到/:post_id/comments(.:format)
因为我可以在本地尝试,所以您可以尝试
<%= link_to "Reply", post_comment_path(:parent_id => comment, :post_id => @post.id), method: :post %>
或手动添加正确的路径,例如
link_to 'foo', :action => :foo, :id => @bar.id, method: :post
或
link_to 'foo', '/foo/#{@bar.id}', method: :post