Ruby on Railsでちょっとした開発を行っているのですが、いいね機能がうまく実装できません。具体的にはチャットルームにお気に入り(いいね)をする機能です。
view/chatrooms/show.html.erb
・・・ <% if user_signed_in? %> <div id="favorite-link"> <%= render "favorites/favorite_links", chatroom: @chatroom %> </div> <% end %> ・・・
view/favorites/_favorite_links.html.erb
・・・ <% if current_user.favorites.find_by(chatroom_id: chatroom.id) %> <%= link_to 'お気に入りを取り消す', unfavorite_path(chatroom.id), method: :delete, remote: true %> <% else %> <%= link_to 'お気に入り', favorite_path(chatroom.id), method: :post, remote: true %> <% end %> ・・・
controllers/favorites_controller.rb
class FavoritesController < ApplicationController def favorite chatroom = Chatroom.find(params[:chatroom_id]) favorite = current_user.favorites.build(chatroom_id: chatroom.id) favorite.save end def unfavorite chatroom = Chatroom.find(params[:chatroom_id]) favorite = current_user.favorites.find_by(chatroom_id: chatroom.id) favorite.destroy end end
view/favorites/favorite.js.erb, unfavorite.js.erb
$("#favorite-link").html('<%= escape_javascript(render("favorites/favorite_links", chatroom: @chatroom)) %>');
お気に入りはきちんと保存され、画面をリロードすれば"お気に入り"、"お気に入りを消す"は切り替わります。ですが、"お気に入り"、"お気に入りを消す"を押した時点では何も変わらない状態です。Rubyのバージョンは4.2.5です。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。