Skip to content

Instantly share code, notes, and snippets.

@chloerei
Last active September 12, 2023 07:24
Show Gist options
  • Save chloerei/82f4589be1bc3a8b87a8c2aa789daa60 to your computer and use it in GitHub Desktop.
Save chloerei/82f4589be1bc3a8b87a8c2aa789daa60 to your computer and use it in GitHub Desktop.
a turbo stream update example
<%
voted = Current.user && post.votes.exists?(user: Current.user)
%>
<div id="<%= dom_id(post, :vote) %>", class="inline-block align-middle">
<% if voted %>
<%= form_with url: site_post_vote_path(post), method: :delete do |form| %>
<%= render "components/button", type: :submit, style: :outlined, label: post.votes_count, icon: :arrow_upward, active: true %>
<% end %>
<% else %>
<%= form_with url: site_post_vote_path(post), method: :post do |form| %>
<%= render "components/button", type: :submit, style: :outlined, label: post.votes_count, icon: :arrow_upward %>
<% end %>
<% end %>
</div>
<div id="<%= dom_id post, :voters %>" class="flex flex-wrap gap-1">
<% if post.voters.any? %>
<% post.voters.order("votes.created_at desc").each do |voter| %>
<a href="#" class="block">
<%= image_tag user_avatar_url(voter), class: "h-10 w-10 rounded-full" %>
</a>
<% end %>
<% else %>
<div class="text-sm text-gray-500">
No voters
</div>
<% end %>
</div>
<%= turbo_stream.replace dom_id(@post, :vote), partial: "sites/votes/button", locals: {post: @post} %>
<%= turbo_stream.replace dom_id(@post, :voters), partial: "sites/votes/voters", locals: {post: @post} %>
class Sites::VotesController < Sites::BaseController
before_action :require_current_user
before_action :set_post
def create
@post.votes.create(user: Current.user, site: Current.site)
render :update
end
def destroy
@post.votes.destroy_by(user: Current.user)
render :update
end
private
def set_post
@post = Current.site.posts.find(params[:post_id])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment