我为我的“帖子”视图创建了一个评论部分,并且在表单上使用了
在评论控制器中保存后,我可以执行
在评论控制器的create操作中保存评论后,我尝试过
评论控制器:
remote: true
,因此当您按下回车并将“新评论”表单提交到数据库时,它会在后台更新(评论已创建,页面不会重定向或更改),但我无法让它在页面上加载评论。您必须刷新页面才能看到它们。在评论控制器中保存后,我可以执行
redirect_to :back
,但这会将用户带到页面顶部而不是停留在原地查看评论。在评论控制器的create操作中保存评论后,我尝试过
render 'posts#show'
,但这会尝试将您发送到/comments/posts/:slug/
。如果它实际上呈现了帖子展示操作,我认为这将起作用。评论控制器:
class CommentsController < ApplicationController
before_action :find_commentable
def show
end
def new
@comment = Comment.new
end
def create
@comment = @commentable.comments.new comment_params
@comment.author = current_user if current_user
@comment.save
end
private
def comment_params
params.require(:comment).permit(:body, :author_id, :post_id)
end
def find_commentable
@commentable = Comment.find(params[:comment_id]) if params[:comment_id]
@commentable = Post.find_by_slug(params[:post_id]) if params[:post_id]
end
end
帖子展示页面上的评论部分:
%ul#post-comments
= render 'comment_feed'
= form_for [@post, Comment.new], remote: true do |f|
= f.text_field :body, class: 'js-new-comment-field', placeholder: "Write a comment..."
posts/show.js.erb:
$("#post-comments").html("<%= escape_javascript render("comment_feed") %>");
Routes.rb:
resources :posts do
collection do
match 'search' => 'posts#search', via: [:get, :post], as: :search # For ransack search
end
resources :comments
end
resources :comments do
resources :comments # Replies on comments
end