Railsでrailsとjsを使ったお手軽「いいね♡機能」をみながら、「いいね♡機能」を実装しているのですが、[いいね!ボタン]を押したあとにリロードしなければ画面が変化しません。Ajaxでリロードなしで変更できるようにしたいのですが、Rails側でエラーが出ているのですが、解決できません。。
エラーメッセージ
Ruby
1 Rendered likes/_like.html.erb (270.1ms) 2 Rendered likes/create.js.erb (288.5ms) 3Completed 500 Internal Server Error in 381ms (ActiveRecord: 21.7ms) 4 5ActionView::Template::Error (undefined local variable or method `micropost' for #<#<Class:0x007f902c142940>:0x007f90284f6658>): 6 1: <% if logged_in? %> 7 2: <% if micropost.like_user(current_user.id) %> 8 3: <%= button_to micropost_like_path(micropost_id: micropost.id, id: 1), method: :delete, id: "like-button", remote: true do %> 9 4: <%= image_tag("hot.png", style: "width: 20px;") %> 10 5: <span>
###該当するソースコード
_like.html.erb
ruby
1<% if logged_in? %> 2 <% if micropost.like_user(current_user.id) %> 3 <%= button_to micropost_like_path(micropost_id: micropost.id, id: 1), method: :delete, id: "like-button", remote: true do %> 4 <%= image_tag("hot.png", style: "width: 20px;") %> 5 <span> 6 <%= micropost.likes_count %> 7 </span> 8 <% end %> 9 <% else %> 10 <%= button_to micropost_likes_path(micropost),id: "like-button", remote: true do %> 11 <%= image_tag("not.png", style: "width: 20px;") %> 12 <span> 13 <%= micropost.likes_count %> 14 </span> 15 <% end %> 16 <% end %> 17<% else %> 18 <%= image_tag("not.png") %> 19 <span> 20 <%= micropost.likes_count %> 21 </span> 22<% end %>
create.js.erb
Ruby
1$("#like-buttons").html("<%= j(render partial: 'like', locals: { microposts: @microposts, likes: @likes, like: @like}) %>")
destroy.js.erb
Ruby
1$("#like-buttons").html("<%= j(render partial: 'like', locals: { microposts: @microposts, likes: @likes }) %>");
likes_controller.rb
Ruby
1class LikesController < ApplicationController 2 def create 3 @like = Like.create(user_id: current_user.id, micropost_id: params[:micropost_id]) 4 @likes = Like.where(micropost_id: params[:micropost_id]) 5 @microposts = Micropost.all 6 end 7 8 def destroy 9 like = Like.find_by(user_id: current_user.id, micropost_id: params[:micropost_id]) 10 like.destroy 11 @likes = Like.where(micropost_id: params[:micropost_id]) 12 @microposts = Micropost.all 13 end 14end
すみませんがどうぞ宜しくお願い致します。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/08/24 07:41 編集
2017/08/24 09:36
2017/08/24 12:48
2017/08/24 15:05
2017/08/25 00:36
2017/08/25 11:22
2018/11/29 03:51
2018/11/30 02:56
2018/11/30 07:48