Rails 4:在将远程表单提交到不同控制器后使用ajax重新加载页面

3
我为我的“帖子”视图创建了一个评论部分,并且在表单上使用了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
2个回答

1

0
我在 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:演示


你解决了吗? - uzaif
还没有,但已经接近了。我没有在服务器端做任何事情,所以也许我只需要弄清楚如何用创建的评论响应ajax请求。到目前为止,这个页面很有帮助:http://guides.rubyonrails.org/working_with_javascript_in_rails.html - Steve Brewer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接