現在、railsとajaxを使っていいね機能を作ろうとしています。現在、問題は二つあるのですが、まず一つ目の問題を解決したいです。いいね機能はサイトのトップページであるindex.html.erbで実装します。トップページには投稿が複数あり、そのそれぞれがいいねができて、灰色のハートを押すと赤いハートに変わる、赤いハートを押すと灰色に変わるといった動きをさせたいです。その際には合計のいいねの数もカウントしてくれます。なので、投稿のいいね機能にはそれぞれには異なったidをもたせています。今回は仮にid0のいいねを押した時のajaxの部分テンプレートの部分テンプレートの置き換えが上手くいかないことです。現在の動きとしてはid0のいいねを押すと画像と合計いいね数は変わるのですが完全に画面が読み込まれず、もう一回押すとTemplate is missingとなります。コードは下記に載せておくので教えていただければ幸いです。
#posts/index.html.erb <% @posts.each_with_index do |post, i| %> <div class="grid-10"> <div class="thumbnail"> <p><%= post.user.nickname %>さん</p> <p>曲名:<%= post.song_title %><br>アーティスト名:<%= post.singer %></p> <div iframe-content> <iframe class="embed-responsive-item" src="<%= post.youtube_url %>"></iframe> </div> <p><%= post.text %></p> <%= render partial: "likes/like", locals: { post: post, i: i} %> <% if user_signed_in? && post.user_id == current_user.id %> <%= link_to '編集', "/posts/#{post.id}/edit" %> <%= link_to '削除', "/posts/#{post.id}", method: :delete %> <% end %> <%= link_to '詳細', "/posts/#{post.id}" %> </div> </div> <% end %>
#likes/_like.html.erb <% if user_signed_in? %> <% if post.like_user(current_user.id) %> <%= button_to "/posts/#{post.id}/unlike",params:{index: i}, method: :delete, id: i, remote: true do %> <%= image_tag("icon_red_heart.svg") %> <span> <%= post.likes_count %> </span> <% end %> <% else %> <%= button_to "/posts/#{post.id}/like",params:{index: i} ,id: i, remote: true do %> <%= image_tag("icon_heart.svg") %> <span> <%= post.likes_count %> </span> <% end %> <% end %> <% else %> <%= image_tag("icon_heart.svg") %> <span> <%= post.likes_count %> </span> <% end %>
#likes/create.js.erb $('#0').html("<%= j(render partial: 'like', locals: { post: @post,i: @index,like:@likes }) %>");
#likes/destroy.js.erb $('#0').html("<%= j(render partial: 'like', locals: { post: @post,i: @index,like:@likes }) %>");
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/10/26 12:59
2016/10/27 23:15
2016/10/29 00:32
2016/11/01 07:18