简体   繁体   English

Rails 4:在将远程表单提交给其他控制器后,使用ajax重新加载页面

[英]Rails 4: Reload page with ajax after submitting remote form to a different controller

I've made a comments section for my 'posts' views and I've got remote: true working on the form so when you hit enter and submit the 'new comment' form to the database, it updates in the background fine (the comment is created, page doesn't redirect or change) but I can't get it to load the comments on the page. 我已经为我的'帖子'视图做了一个评论部分,我已经remote: true在表单上工作remote: true ,所以当你点击进入并将'新评论'表单提交到数据库时,它会在后台更新(注释已创建,页面未重定向或更改)但我无法在页面上加载注释。 You have to refresh the page to see them. 您必须刷新页面才能看到它们。

I could do redirect_to :back in the comments controller after saving but that takes user to top of the page rather than staying put to see the comment appear. 我可以在保存之后在评论控制器中执行redirect_to :back但是这redirect_to :back用户带到页面的顶部,而不是留在看到注释出现。

I've tried render 'posts#show' after saving the comment in the comment controller create action but that tries to send you to /comments/posts/:slug/ . 我在注释控制器创建操作中保存注释后尝试render 'posts#show' ,但尝试将您发送到/comments/posts/:slug/ If it actually rendered the posts show action I think this would work. 如果它实际上使帖子显示动作我认为这将有效。

Comments 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

Comment section on post show 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: 文章/ show.js.erb:

$("#post-comments").html("<%= escape_javascript render("comment_feed") %>");

Routes.rb: 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

I added this second match line to routes.rb and it's refreshing the page with the new comment now: 我将第二个匹配行添加到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

It's not ajax though: demo 它不是ajax: demo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM