Ajaxを使って、非同期でフォローする/アンフォローするを作っています。
そしてそのボタンが押されると、フォロワー数やボタンに変化を加えたいです。
しかしながら、Controller内のrespond_toの箇所からの反応が見れません。
html
1<strong id="followers"> 2 <p> フォロワー <%= @follower_count %></strong> 3<strong id="following"> 4 フォロー中 <%= @followed_count %></strong> 5 </p> 6 7<div id="follow_form"> 8 <% if @current_user.following?(@user) %> 9 <storng id="follower_btn"> 10 <%= render 'unfollow' %> 11 <% else %> 12 <%= render 'follow' %> 13 </storng> 14 <% end %> 15</div>
renderで送っているフォロー/アンフォローボタンは正常に表示されています。
Controller
1 def create 2 @current_user.follow(@user) 3 respond_to do |format| 4 format.html { redirect_to @user } 5 format.js 6 end 7 end 8 def destroy 9 @current_user.unfollow(@user) 10 respond_to do |format| 11 format.html { redirect_to @user } 12 format.js 13 end 14 end
js
1create.js.erb: 2$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>"); 3$("#followers").html("<%= @follower_count %>"); 4$("#follower_btn").html('<%= button_to "フォローする", friendships_path(user_id: @user.id), method: :post, :remote=>true, :class => "follow-btn" %>'); 5 6destroy.js.erb 7$("#follow_form").html("<%= escape_javascript(render('users/follow')) %>"); 8$("#following").html('<%= @follower_count %>'); 9$("#follower_btn").html('<%= button_to "フォロー中", friendship_path(user_id: @user.id), method: :delete, :remote=>true, :class => "follow-btn" %>');
(js.erbの三行目はrenderで送ったfollowとunfollowの記述内容です。)
現状、フォローボタンを押すと、手動でページ更新をした場合に、フォローボタンがアンフォローボタンに切り替わります。
そこでControllerの一行目を抜くと、フォロー/アンフォローは機能しません。
そこで推測するに、Controller一行目でサーバーへの送信はできているのですが、その後のrespond_to処理は機能せずにいることにより、jsの記載内容が自動更新されずにいると考えています。
ですが自分では解決にできずにいます、解決方法をお分かりの方、ぜひお教え頂ければ幸いです。
あなたの回答
tips
プレビュー