我是Ruby on Rails的新手,所以我决定做railstutorial.org的教程。我坚持第12章,列出12.37-38。我将所有html.erb文件转换为html.haml(在第7章中)。我希望Ajax在单击Follow / Unfollow按钮后替换partials但是现在当我点击例如按照按钮,取消关注按钮出现在上方跟随,此按下按钮不会消失。
是这样的:http://i.imgur.com/RjwTsUU.png。之后,当我点击上方按钮时,它会成功替换Follow / Unfollow partials的渲染,但上面的按钮(在本例中为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 %>');
show.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 partial:
- 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
答案 0 :(得分:0)
根据chapter where this feature is described,您并未使用正确的语法进行渲染调用。它应该是:
$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>");
$("#followers").html('<%= @user.followers.count %>');
请注意包围&#39; users / unfollow&#39;的渲染调用后的额外括号 - 您的其他电话也是如此:
$("#follow_form").html("<%= escape_javascript(render('users/follow')) %>");
$("#followers").html('<%= @user.followers.count %>');
希望有所帮助。