#app/views/comments/_comment.html.erb <%= content_tag :div, id: dom_id(comment), class: "card mb-3" do %> <div class="card-body"> <h5 class="card-title"><%= comment.user.email %> said:</h5> <p class="card-text"><%= comment.content %></p> <p id='<%= dom_id(comment)%>_count'> <%= comment.vote_count %> </p> <%= link_to "Up Vote", comment_votes_path(comment, choice: :up_vote, format: :turbo_stream), class: "card-link" %> <%= link_to "Down Vote", comment_votes_path(comment, choice: :down_vote, format: :turbo_stream), class: "card-link" %> </div> <% end %>
# app/models/vote.rb after_update_commit do broadcast_update_to("comments", target: "#{dom_id(comment)}_count", html: comment.vote_count) end
class VotesController < ApplicationController ... def show @comment = Comment.find(params[:comment_id]) @vote = Vote.find_or_create_by(user: current_user, comment: @comment) @vote.voted(params[:choice]) end
class Vote < ApplicationRecord ... def voted(choice) return unless choice.in?(Vote::choices.keys) case choice when 'up_vote' up_vote? ? cancel! : up_vote! when 'down_vote' down_vote? ? cancel! : down_vote! end end