Skip to content

Commit 69e58d8

Browse files
committed
Using Turbo Streams
1 parent 28dff0b commit 69e58d8

File tree

6 files changed

+33
-12
lines changed

6 files changed

+33
-12
lines changed

app/controllers/likes_controller.rb

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,21 @@ class LikesController < ApplicationController
22
before_action :set_post, only: %w[create destroy]
33

44
def create
5-
Current.user.likes.create(post: @post)
5+
respond_to do |format|
6+
Current.user.likes.create(post: @post)
67

7-
redirect_to root_path
8+
format.html { redirect_to root_path }
9+
format.turbo_stream
10+
end
811
end
912

1013
def destroy
11-
Current.user.likes.find_by(post: @post).destroy
14+
respond_to do |format|
15+
Current.user.likes.find_by(post: @post).destroy
1216

13-
redirect_to root_path
17+
format.html { redirect_to root_path }
18+
format.turbo_stream
19+
end
1420
end
1521

1622
private

app/views/likes/_like.html.erb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
<div>
1+
<turbo-frame id="likes">
22
<% if user.likes.exists?(post: post) %>
33
<%= button_to post_like_path(post, user.likes.find_by(post: post)), method: :delete do %>
44
Unlike
@@ -8,4 +8,4 @@
88
Like
99
<% end %>
1010
<% end %>
11-
</div>
11+
</turbo-frame>
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<%= turbo_stream.replace "likes" do %>
2+
<%= render partial: "likes/like", locals: { user: Current.user, post: @post } %>
3+
<% end %>
4+
5+
<%= turbo_stream.replace "title" do %>
6+
<%= render partial: "posts/title", locals: { post: @post } %>
7+
<% end %>
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<%= turbo_stream.replace "likes" do %>
2+
<%= render partial: "likes/like", locals: { user: Current.user, post: @post } %>
3+
<% end %>
4+
5+
<%= turbo_stream.replace "title" do %>
6+
<%= render partial: "posts/title", locals: { post: @post } %>
7+
<% end %>

app/views/posts/_title.html.erb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<h1 id="title">
2+
<%= post.title %>
3+
(<%= pluralize(post.likes.count, "like") %>)
4+
</h1>

app/views/posts/show.html.erb

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
1-
<main>
2-
<article style="margin-top: 200vh">
3-
<h1>
4-
<%= @post.title %>
5-
(<%= pluralize(@post.likes.count, "like") %>)
6-
</h1>
1+
<main style="height: 300px; overflow-y: scroll">
2+
<article style="margin-top: 50vh">
3+
<%= render partial: "title", locals: { post: @post } %>
74

85
<p>
96
<%= @post.content %>

0 commit comments

Comments
 (0)