Ajax escape_javascript 方法不会删除 Rails 中先前渲染的部分

Ajax escape_javascript method does not delete previous rendered partial in Rails

我是 Rails Ruby 的新人,所以我决定学习 railstutorial.org 的教程。我停留在第 12 章,列出 12.37-38。我将所有 html.erb 文件转换为 html.haml(在第 7 章中)。我希望 Ajax 在单击 Follow/Unfollow 按钮后替换部分,但现在当我单击例如关注按钮,取消关注按钮出现在关注上方,并且此关注按钮不会消失。

诸如此类:http://i.imgur.com/RjwTsUU.png

之后,当我点击上方的按钮时,它成功地替换了 Follow/Unfollow 部分的呈现,但上方的按钮(在本例中为 Follow)将可见,直到页面被刷新。我做错了什么?

destroy.js.erb:

$("#follow_form").html("<%= escape_javascript(render 'users/follow' ) %>");
$("#followers").html('<%= @user.followers.count %>');

create.js.erb:

$("#follow_form").html("<%= escape_javascript(render 'users/unfollow' ) %>");
$("#followers").html('<%= @user.followers.count %>');

显示.html.haml:

- provide(:title, @user.name)
.row
  %aside.col-md-4
    %section.user_info
      %h1 
        = gravatar_for @user
        = @user.name
    %section.stats
      = render 'shared/stats'
  .col-md-8
    = render 'follow_form' if logged_in?
    - if @user.microposts.any?
      %h3 
        Microposts (#{@user.microposts.count})
      %ol.microposts
        = render @microposts
      = will_paginate @microposts

follow_form 部分:

- unless current_user?(@user)
  %div#follow_form
  - if current_user.following?(@user)
    = render 'unfollow'
  - else
    = render 'follow'

取消关注部分:

= form_for(current_user.active_relationships.find_by(followed_id: @user.id), html: { method: :delete}, remote: true) do |f| 
  = f.submit "Unfollow", class: "btn"

关注部分:

= form_for(current_user.active_relationships.build, remote: true) do |f| 
  %div
    = hidden_field_tag :followed_id, @user.id
  = f.submit "Follow", class: "btn btn-primary"

relationships_controller.rb:

class RelationshipsController < ApplicationController
  before_action :logged_in_user

  def create
    @user = User.find(params[:followed_id])
    current_user.follow(@user)
    respond_to do |format|
      format.html { redirect_to @user }
      format.js
    end 
  end 

  def destroy
    @user = Relationship.find(params[:id]).followed
    current_user.unfollow(@user)
    respond_to do |format|
      format.html { redirect_to @user }
      format.js
    end 
  end 
end

根据 chapter where this feature is described 的说法,您没有为渲染调用使用正确的语法。应该是:

$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>");
$("#followers").html('<%= @user.followers.count %>');

请注意环绕 'users/unfollow' 的渲染调用后的额外括号 - 您的其他调用也是如此:

$("#follow_form").html("<%= escape_javascript(render('users/follow')) %>");
$("#followers").html('<%= @user.followers.count %>');  

希望对您有所帮助。