我已经为我的“帖子” View 创建了一个评论部分,并且我有 remote: true
正在处理表单,因此当您按下回车键并将“新评论”表单提交到数据库,它在后台正常更新(评论已创建,页面不会重定向或更改)但我无法让它在页面上加载评论。您必须刷新页面才能看到它们。
保存后,我可以在评论 Controller 中执行 redirect_to :back
操作,但这会将用户带到页面顶部,而不是留在原地查看评论出现。
在评论 Controller 创建操作中保存评论后,我尝试了 render 'posts#show'
但它试图将您发送到 /comments/posts/:slug/
。如果它实际上呈现了帖子显示 Action ,我认为这会起作用。
评论 Controller :
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
秀后 View 的评论部分:
%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") %>");
路线.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
最佳答案
关于ruby-on-rails - rails 4 : Reload page with ajax after submitting remote form to a different controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41522270/