我正在尝试在我的 Rails 4 应用程序中添加评论。我已经能够使用 Railcasts 262 作为指南来获得嵌套注释。当用户想要回复评论或添加新评论并限制页面重新加载的时间时,我想让新的评论字段出现。我看过 Railscasts 136 等。我正在使用祖先 gem,无法根据需要显示表单和评论。
问题似乎是当我将用户发送到 new_comment_path 时,post_id 会丢失。在路由中添加 ajax 和新步骤之前,我已经能够将其与注释一起保存。在我只是在帖子显示页面上呈现评论表单之前它起作用了。现在新评论正在保存,但 post_id、ancestry_id 和 parent_id 都是 nil。因此,我无法将这些评论呈现在帖子的显示页面上。在我让 new_comment 工作后,我还将对其进行设置,以便“回复”也可以工作。如果您有任何建议,请告诉我。谢谢。
post.rb
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
评论.rb
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
has_ancestry
end
_comment_form.html.erb
<%= form_for @comment, remote: true do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="comment_field">
<%= f.hidden_field :post_id, :value => @comment.post_id %>
<%= f.hidden_field :parent_id, :value => params[:parent_id] %>
<%= f.text_area :content, placeholder: "" %>
</div>
<button class="btn" type="submit">
Send request
</button>
<% end %>
发布 show.html.erb
... information about post ...
<div id="added_comments">
<%= link_to "New Comment", new_comment_path, id: "new_link", remote: true, :post => @post %>
</div>
<%= nested_comments @post.comments.arrange(:order => :created_at) %>
评论 new.html.erb
<h1>New Comment</h1>
<%= render 'comment/form' %>
评论 new.js.erb
$('#new_link').hide().after('<%= j render("form") %>');
创建.js.erb
$('#new_comment').remove();
$('#new_link').show();
$('#added_comments').append('<%= j nested_comments (@post.comments).arrange(:order => :created_at) %>');
_comment.html.erb
<%= link_to comment.user.name, comment.user %>
<%= comment.content %>
<%= link_to "Reply", post_path(@post, :parent_id => comment) %>
评论控制器.rb
def new
@comment = Comment.new(:parent_id => params[:parent_id], :post_id => params[:post_id])
end
def create
@comment = Comment.create(comment_params)
@comment.user = current_user
if @comment.save
CommentMailer.comment_confirmation(@comment).deliver
flash[:success] = "Comment added."
respond_to do |format|
format.html { redirect_to :back }
format.js
end
else
flash[:error] = "Comment cannot be blank"
end
end
def show
@comment = Comment.find(params[:id])
@user = @comment.user
end
post_controller.rb
def show
@post = Post.find(params[:id])
@comment = @post.comments.build(:parent_id => params[:parent_id])
@user = User.find(@post.user_id)
@comment.user_id = current_user
end
def create
@post = current_user.posts.build(post_params)
if @post.save
flash[:success] = "Post added!"
redirect_to root_url
else
@repository_items = [ ]
render 'shared/_post_form'
end
end