我试图在rails中为我的评论实施回复。我正在观看此视频作为指南http://railscasts.com/episodes/262-trees-with-ancestry 我创建的所有注释都成为根节点,每次我尝试回复注释时,它似乎都没有注册为子节点。 (我已经使用rails控制台进行了检查,并且回复评论的栏目' ancestry'总是为零)
我的评论是Post Model下的嵌套资源。我怀疑问题出在评论控制器中的create函数?
使用rails' 4.2.4'
评论控制员:
def new
@post = Post.find(params[:post_id])
@comment = @post.comments.build
@comment.parent_id = params[:parent_id]
end
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(comment_params)
@comment.user = current_user
if @comment.save
redirect_to build_post_path(@post)
else
redirect_to build_post_path(@post)
end
end
评论/ new.html.erb
<div class = "row">
<div class="col-md-8 col-md-offset-2 ">
<h3>Reply</h3>
<ol class ="comments">
<%= render @comment.parent if @comment.parent %>
</ol>
</div>
</div>
<%= render 'form' %>
评论/ _form.html.erb
<div class = "row">
<div class = "col-md-5 col-md-offset-2">
<%= form_for([@post, Comment.new]) do |f| %>
<%= render 'shared/error_messages',object: f.object %>
<%= f.hidden_field :parent_id %>
<%= f.label :comment %>
<%= f.text_area :comment , class: 'form-control', rows: "4" %>
<div class = "row">
<div class = "col-md-3">
<%= f.submit "Submit", class: "btn btn-primary" %>
</div>
</div>
<% end %>
</div>
</div>
评论/ _comments.html.erb
<li id="comment-<%= comment.id %>">
<span class="avatar"><%= image_tag(comment.user.avatar.url(:thumb)) %></span>
<span class="user"><%= link_to comment.user.name, comment.user %> <span class = "timestamp"><%= time_ago_in_words(comment.created_at) %> ago.</span></span>
<span class="content"><%= comment.comment %></span>
<span class="options">
<%= link_to "Index", post_comments_path %> |
<%= link_to "Reply", new_post_comment_path(:parent_id => comment) %> |
<% if current_user?(comment.user) %>
<%= link_to "Delete", [comment.post, comment], method: :delete,
data: { confirm: "You sure?" } %>
<%= link_to "Edit", edit_post_comment_path(comment.post, comment) %>
<% end %>
</span>
</li>
交/ show.html.erb
<div class = "row">
<div class="col-md-8 col-md-offset-2 ">
<h3>Comments (<%= @post.comments.count %>)</h3>
<ol class ="comments">
<%= nested_messages @post.comments.arrange(:order => :created_at) %>
</ol>
</div>
</div>
帮助方法
def nested_messages(messages)
messages.map do |message, sub_messages|
render(message) + content_tag(:div, nested_messages(sub_messages), :class => "nested_messages")
end.join.html_safe
end
答案 0 :(得分:0)
您在表单声明中调用了Comment.new,尽管您已在新方法中发起了新注释,将表单调用更改为:
<%= form_for([@post, @comment]) do |f| %>
我认为通过添加,您不必手动设置parent_comment的值。