ruby-on-rails - rails 4 : Reload page with ajax after submitting remote form to a different controller

标签 ruby-on-rails ajax render

我已经为我的“帖子” 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/

相关文章:

javascript - ajax 中的 Laravel Blade 状况

html - 有条件地渲染 .hbs 模板 emberjs

Primefaces 保存/通过过滤数据表结果列表

java - Wicket 6.13 链接 onclick 行为不适用于 ajax onclick 行选择

javascript - 在包含 html 的变量中选择一个元素

android - 在 Android 中格式化多行 TextView 的第一行

ruby-on-rails - 是否可以从 Thor 脚本中调用 Git 或其他命令行工具?

ruby-on-rails - Ruby 无法加载此类文件 -- dm--adapter (LoadError)

ruby-on-rails - 将数组的数组拆分,[0] 拆分为一个,[1] 拆分为另一个

ruby-on-rails - 在路由中捕获所有内容时重定向并引发 flash 消息