0
0
Ruby on Railsframework~30 mins

Stimulus and Turbo (Hotwire) in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Build a Simple Like Button with Stimulus and Turbo
📖 Scenario: You are creating a small interactive feature for a blog post page. Readers can click a like button to increase the like count without reloading the page.This uses Stimulus to handle the button click and Turbo to update the like count dynamically.
🎯 Goal: Build a like button that increments the like count on click using Stimulus controller and Turbo frame updates.
📋 What You'll Learn
Create a Turbo Frame with a unique ID to wrap the like count
Create a Stimulus controller named like to handle button clicks
Add a data-action to the button to call the Stimulus controller method
Update the like count inside the Turbo Frame without full page reload
💡 Why This Matters
🌍 Real World
This pattern is common in modern Rails apps to create fast, interactive UI elements without full page reloads, improving user experience.
💼 Career
Understanding Stimulus and Turbo is essential for Rails developers building responsive, real-time features efficiently.
Progress0 / 4 steps
1
Set up the Turbo Frame and initial like count
Create a Turbo Frame tag with id="like_count_frame" that contains a span showing the initial like count of 0.
Ruby on Rails
Need a hint?

Use the <turbo-frame> tag with the exact id="like_count_frame" and put a <span> inside showing 0.

2
Add the Stimulus controller and button
Add a button with data-controller="like" and data-action="click->like#increment". The button text should be Like.
Ruby on Rails
Need a hint?

Add a <button> with the exact data-controller="like" and data-action="click->like#increment" attributes and text 'Like'.

3
Create the Stimulus controller with increment method
Create a Stimulus controller named like_controller.js with an increment method that fetches the Turbo Frame with id="like_count_frame" and updates its inner span by increasing the number by 1.
Ruby on Rails
Need a hint?

Inside increment(), get the element with id="like_count_frame", find the span, read its number, add 1, and update the text.

4
Connect Stimulus controller in HTML and finalize
Ensure the Stimulus controller is loaded by adding data-controller="like" to the button and that the Turbo Frame and button are inside the same HTML snippet. Confirm the button click updates the like count inside the Turbo Frame.
Ruby on Rails
Need a hint?

Make sure the button has data-controller="like" and data-action="click->like#increment" and the Turbo Frame is present in the HTML.