ruby-on-rails – 无法让Ajax在follow / unfollow按钮上工作 –
我不能让Ajax在我的Rails应用程序中工作.
借助Ajax的神奇之处:当我点击“关注”按钮时,它应该更新用户在个人资料页面中看到的关注者数量,而无需刷新页面.但是,我的示例应用程序中没有发生这种情况. 发生的事情是,“跟随”按钮,当点击时,变为“取消关注”,因为它应该但是,跟随者的数量保持不变,直到我点击网络浏览器中的刷新按钮(在FF和IE中测试).我正在关注Michael Hartl的railstutorial.org,使用Rails 4和Ruby 2.0.0p195. 这是我从FireFox获得的控制台消息: 传递给getElementById()的空字符串. 这是我下面的代码,视图中的“跟随”按钮对应于关系控制器中的操作,它们应该命中create.js.erb和destroy.js.erb部分. -CONTROLLER- def create @user = User.find(params[:relationship][:followed_id]) current_user.follow!(@user) # redirect_to @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) # redirect_to @user respond_to do |format| format.html { redirect_to @user } format.js end end -JAVASCRIPT- $("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>"); $("#followers").html('<%= @user.followers.count %>'); _destroy.js.erb: $("#follow_form").html("<%= escape_javascript(render('users/follow')) %>"); $("#followers").html('<%= @user.followers.count %>'); -VIEWS-是follow_form,带有_follow.html.erb和_unfollow.html.erb. _follow_form.html.erb <% unless current_user?(@user) %> <div id="follow_form"> <% if current_user.following?(@user) %> <%= render 'unfollow' %> <% else %> <%= render 'follow' %> <% end %> </div> <% end %> _follow.html.erb: <%= form_for(current_user.relationships.build(followed_id: @user.id),remote: true) do |f| %> <div><%= f.hidden_field :followed_id %></div> <%= f.submit "Follow",class: "btn btn-large btn-primary" %> <% end %> _unfollow.html.erb <%= form_for(current_user.relationships.find_by(followed_id: @user),html: { method: :delete },remote: true) do |f| %> <%= f.submit "Unfollow",class: "btn btn-large" %> <% end %> 注意 – 我在开发时使用postgreSQL而不是在railstutorial中使用的SQLlite. 编辑回应: <% @user = @user || current_user %> <div class="stats"> <a href="<%= following_user_path(@user) %>"> <strong id="following" class="stat"> <%= @user.followed_users.count %> </strong> following </a> <a href="<%= followers_user_path(@user) %>"> <strong id="following" class="stat"> <%= @user.followers.count %> </strong> followers </a> </div> 解决方法
因为在_stats.html.erb文件中,您没有包含id关注者的元素.请看你的代码
<a href="<%= followers_user_path(@user) %>"> <strong id="following" class="stat"> <%= @user.followers.count %> </strong> followers </a> 它应该是 <a href="<%= followers_user_path(@user) %>"> <strong id="followers" class="stat"> <%= @user.followers.count %> </strong> followers </a> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |