[英]Rails 4: Reload page with ajax after submitting remote form to a different controller
我已经为我的'帖子'视图做了一个评论部分,我已经remote: true
在表单上工作remote: true
,所以当你点击进入并将'新评论'表单提交到数据库时,它会在后台更新(注释已创建,页面未重定向或更改)但我无法在页面上加载注释。 您必须刷新页面才能看到它们。
我可以在保存之后在评论控制器中执行redirect_to :back
但是这redirect_to :back
用户带到页面的顶部,而不是留在看到注释出现。
我在注释控制器创建操作中保存注释后尝试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..."
文章/ 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
我将第二个匹配行添加到routes.rb,它现在用新注释刷新页面:
resources :posts do
collection do
match 'search' => 'posts#search', via: [:get, :post], as: :search
match '/comments/posts/:slug' => 'posts#show', via: [:get, :post], as: :comment
end
resources :comments
end
它不是ajax: demo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.