我正在尝试创建一个功能,用户可以单击取消关注按钮通过ajax销毁友谊,但是,即使控制台说destroy.js.erb成功呈现,也不会删除div。期望的结果:当用户单击取消关注时,记录将从关注者页面中删除。我的代码对我来说似乎合乎逻辑,有人能指出我哪里出错了吗?
友谊/ destroy.js.erb
$('#following following_<%= @follow.id %>').remove();
$('#following h3').html("You are following <%= pluralize(current_user.active_friends.count, 'person') %>");
class FriendshipsController < ApplicationController
def destroy
@friendship = Friendship.find_by(id: params[:id])
@follow = @friendship.friend
if @friendship.destroy
if @friendship.accepted? == true
respond_to do |format|
format.html { redirect_to followers_path, :flash => { :success => "You have unfollowed #{@friendship.user.name}."} }
format.js
end
else
respond_to do |format|
format.html { redirect_to followers_path, :flash => { :success => "You have declined #{@friendship.user.name}'s follow request."} }
format.js
end
end
else
flash[:error] = "Sorry! Could not unfollow user/decline follow request!"
redirect_back fallback_location: root_path
end
end
end
users / following.html.erb(显示正在关注的用户列表的页面)
<div class = "container" id="following">
<h3 class = "padding-bottom-40">You are following <%= pluralize(@following.count, 'person') %></h3>
<% @following.each do |follow| %>
<div class="row alternate-row" id ="#following_<%= follow.id %>">
<div class = "col-md-1 col-xs-2">
<%= gravatar_for(follow, size: 45) %>
</div>
<div class = "col-md-9 col-xs-6">
<b><%= link_to follow.name, user_path(follow) %></b><br>
<p><%= pluralize(follow.articles.count, "article") if follow.articles %></p>
</div>
<div class = "col-md-2 col-xs-4">
<%= link_to "Unfollow", friendship_path(current_user.friendships.find_by_friend_id(follow.id)), :method => :delete, remote: true, data: { confirm: "Are you sure?" }, class:"btn btn-md btn-danger" %>
</div>
</div>
<% end %>
</div>
用户控制器
class UsersController < ApplicationController
def following
@following = current_user.active_friends.all
end
end
架构:
用户是提交跟随请求的人,朋友是用户想要关注的人。
create_table "friendships", force: :cascade do |t|
t.integer "user_id"
t.integer "friend_id"
t.boolean "accepted", default: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
答案 0 :(得分:0)
从id属性中删除#
:
<div class="row alternate-row" id="following_<%= follow.id %>">
...
</div>
let one = $('#one')
let two = $('#two')
console.log(one.attr('id'))
console.log(two.attr('id'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one"></div>
<div id="#two"></div>