タイトル通りですが、ajaxを使って、画面の更新無しにいいねをしたいです。
その際は、ボタンの色といいね数を変更させたいです。
https://qiita.com/YuitoSato/items/94913d6a349a530b2ea2
などを参考作ったりもしたのですが、全く反応がなく困っています。
(いいねのcreate/destroyもボタンや数の変化の反応)
また他のサイトに記載のコードでも試したのですが、うまく行っていません。
jsを取り入れる前にRailsでは何か設定しないといけないとかあるのでしょうか。
Model
1class Like < ApplicationRecord 2 belongs_to :user 3 belongs_to :post, counter_cache: :likes_count 4end
Controller
1class PostsController < ApplicationController 2 def index 3 @posts = Post.all.order(created_at: :desc) 4 @post = Post.find_by(id: params[:id]) 5 @likes_count = Like.where(post_id: @post).count 6 end 7class LikesController < ApplicationController 8 def create 9 @like = Like.create(user_id: @current_user.id, post_id: params[:post_id]) 10 @likes = Like.where(post_id: params[:post_id]) 11 @posts = Post.all 12 end 13 def destroy 14 @like = Like.find_by(user_id: @current_user.id, post_id: params[:post_id]) 15 @like.destroy 16 @likes = Like.where(post_id: params[:post_id]) 17 @posts = Post.all 18 end 19end
View
1 <% if Like.find_by(user_id: @current_user.id, post_id: post.id) %> 2 <%= link_to("/likes/#{post.id}/destroy", :method => :post, id: "like-button", remote: true ) do %> 3 <span class="fa fa-heart fa-2x like-btn-unlike"></span> 4 <span><%= @likes_count %></span> 5 <% end %> 6 <% else %> 7 <%= link_to("/likes/#{post.id}/create", :method => :post, id: "like-button", remote: true) do %> 8 <span class="fa fa-heart fa-2x like-btn"></span> 9 <span><%= @likes_count %></span> 10 <% end %> 11 <% end %>
js
1create.js.erb 2$("#like-buttons").html("<%= j(render partial: 'like', locals: { posts: @posts, likes: @likes, like: @like}) %>") 3destroy.js.erb 4$("#like-buttons").html("<%= j(render partial: 'like', locals: { posts: @posts, likes: @likes }) %>");
jsファイルはview/likesに保存されています。
jsは全くいじってこなかったのですが、初心者でも作れるいいね!機能のやり方を教えてください。
追記:
実際にいいねボタンを押すと、このようなエラーがコンソールで出ています。
error
1ActionView::Template::Error (Missing partial likes/_like, application/_like with {:locale=>[:ja], :formats=>[:js, "application/ecmascript", "application/x-ecmascript", :html, :text, :css, :ics, :csv, :vcf, :vtt, :png, :jpeg, :gif, :bmp, :tiff, :svg, :mpeg, :mp3, :ogg, :m4a, :webm, :mp4, :otf, :ttf, :woff, :woff2, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip, :gzip], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :coffee, :jbuilder]}. Searched in: 2 * "/Users/TOM/myapp/app/views" 3): 4 1: $("#like-buttons").html("<%= j(render partial: 'like', locals: { posts: @posts, likes: @likes, like: @like}) %>") 5 6app/views/likes/create.js.erb:1:in `_app_views_likes_create_js_erb__364044909247640962_70328458376380'
よろしくお願いします。
回答1件