未从呈现的表单显示注释



我是 Ruby 的新手,我正在尝试在我的节目页面上显示评论,但当我创建评论时,它没有显示。我已经在我的节目页面上渲染了部分以显示评论,但它们没有出现。

奇怪的是创建操作有效,但它将我带到此页面:http://localhost:3000/hairstyles/2/comments上面没有任何内容(在我的应用程序中,此页面位于 views>comments>create.html.erb 下),相反,我希望它转到发型的视图页面并显示评论......

如果有人可以提供帮助并查看我的代码中是否有任何错误,我将不胜感激。提前谢谢。

注释控制器:

class CommentsController < ApplicationController
def new
@hairstyle = Hairstyle.find(params[:hairstyle_id])
@comment = Comment.new
end
def create
@comment = Comment.new(comment_params)
@hairstyle = Hairstyle.find(params[:hairstyle_id])
@comment.save   
end
def destroy
end
end
private
def comment_params
params.require(:comment).permit(:content)
end

发型视图页面,我想在其中显示评论:

<div class="container">
<div>
<%= cl_image_tag @hairstyle.photo, width: 300, height: 200, crop: :fill %>
<h1><%= @hairstyle.name %></h1>
<p><%= @hairstyle.description%></p>
<p><%= @hairstyle.category%></p>
<p><%= @hairstyle.video_url %></p>
</div>
</div>
<div>
<%= link_to 'Back', hairstyles_path %>
</div>
<h6>Comments for: <%= @hairstyle.name %> <small><%= %></small></h6>
<h2>
<%= pluralize @hairstyle.comments.size, "comment" %>
</h2>
<div id="comments">
<% if @hairstyle.comments.blank? %>
Be the first to leave a comment for <%= @hairstyle.name %>
<% else %>
<% @hairstyle.comments.each do |comment| %>
<%= render 'comments/show', comment: comment %>
<% end %>
<% end %>
</div>
<%= render 'comments/form', comment: @comment %>

我正在渲染的评论表单确实有效并显示: views>comments>_form.html.erb

<div class="flex-box">
<%= simple_form_for([ @hairstyle, comment ]) do |form| %>
<%= form.input :content, as: :text %>
<%= form.button :submit %>
<% end %>
</div>

我正在渲染的评论内容,一旦我在节目页面上为我的发型添加了评论,就不会显示:

views>comments>_show.html.erb

<p><%= comment.content %></p>

rails 控制器的默认行为是它将在创建方法之后重定向到索引页。 这就是您被重定向到该路径的原因。

您可以简单地在注释控制器的create方法中使用redirec_to,如下所示

def create
@comment = Comment.new(comment_params)
@hairstyle = Hairstyle.find(params[:hairstyle_id])
@comment.save   
redirect_to hairstyle_path(@comment.hairstyle)
end

您从不将您的评论链接到您的发型,您的评论hairstyle_idnil这就是为什么@hairstyle.comments返回一个空数组的原因

def create
@hairstyle = Hairstyle.find(params[:hairstyle_id])
@comment = @hairstyle.comments.build(comment_params)
# equivalent to:
# comment = Comment.new(comment_params)
# comment.hairstyle = @hairstyle
if comment.save
redirect_to hairstyle_path(@hairstyle)
else 
# handle errors
end
end

最新更新