Ruby on Rails: Integration Options for Stimulus

Discover in our tutorial how to easily enhance the interactivity of your Ruby on Rails application with Stimulus. From setup to integration – we guide you step-by-step through the process. Leverage the power of Stimulus to optimize user experience and reduce load times.

In developing Ruby on Rails projects, you may encounter the need for interactivity in generated HTML files. There are various ways to implement this interactivity. One option is to use a JavaScript framework like React or Ember, which work well for Single Page Applications (SPAs), especially when managing client-side state or addressing performance issues related to frequent server requests.

However, implementing a framework to manage state and frequent updates on the client-side requires consideration of several factors:

  1. Performance can be limited by loading and conversion requirements, such as parsing JavaScript and retrieving and converting JSON to HTML.
  2. Committing to a framework can lead to writing more code than necessary for a specific use case, especially when only minor JavaScript enhancements are needed.
  3. Managing state on both client and server sides can lead to task duplication and increased error potential.

As an alternative, the team at Basecamp, who also developed Rails, created Stimulus.js. Described as “a modest JavaScript framework for the HTML you already have,” Stimulus is designed to enhance a modern Rails application by working with server-rendered HTML. State is stored in the Document Object Model (DOM), and the framework provides standard methods for interacting with elements and events in the DOM. It works alongside Turbolinks (included in Rails 5+ by default) to improve performance and load times with code focused on a specific purpose.

Step-by-Step Guide to Integrating Stimulus

Step 1: Creating a Nested Model

The first step is to create a nested Post model that links to our existing Shark model. This involves establishing Active Record relationships between our models: Posts belong to specific Sharks, and each Shark can have multiple Posts.


# app/models/post.rb
class Post < ApplicationRecord
belongs_to :shark
end


# app/models/shark.rb
class Shark < ApplicationRecord
has_many :posts, dependent: :destroy
validates :name, presence: true, uniqueness: true
validates :facts, presence: true
end
Step 2: Creating a Controller for a Nested Resource

Creating a Posts controller involves defining a nested resource route in the application’s main route file and creating the controller file itself to specify the methods associated with particular actions.


# app/controllers/posts_controller.rb
class PostsController < ApplicationController
before_action :get_shark

def create
@post = @shark.posts.create(post_params)
end

def destroy
@post = @shark.posts.find(params[:id])
@post.destroy
end

private

def get_shark
@shark = Shark.find(params[:shark_id])
end

def post_params
params.require(:post).permit(:body, :shark_id)
end
end

Step 3: Reorganizing Views with Partials

In this step, we’ll organize the views and partials that will serve as a foundation for working with Stimulus.



<%= render ‘sharks/posts’ %>
<%= render ‘sharks/all’ %>
Step 4: Installing Stimulus – Ruby on Rails

The first task when using Stimulus is to install and configure it in your application. This involves ensuring that we have the correct dependencies, including the Yarn package manager and Webpacker, the gem that lets us work with the JavaScript preprocessor and bundler webpack. With these dependencies, we can install Stimulus and use JavaScript to manipulate events and elements in the DOM.


# Installing Yarn
sudo apt update
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add –
echo “deb https://dl.yarnpkg.com/debian/ stable main” | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt update
sudo apt install yarn

# Installing webpacker and Stimulus
nano Gemfile # add ‘webpacker’, ‘~> 4.x’ to dependencies
bundle install
bundle exec rails webpacker:install
bundle exec rails webpacker:install:stimulus

Part 5: Core Concepts of Stimulus

Before diving into using Stimulus in Rails partials, it’s important to understand the core concepts of Stimulus:

  • Controllers: JavaScript classes defined in JavaScript modules that allow access to specific HTML elements and the Stimulus application instance.
  • Targets: Allow referencing specific HTML elements and are associated with specific controllers.
  • Actions: Control how DOM events are handled by controllers and are also associated with specific controllers. They create a link between the HTML element associated with the controller, the methods defined in the controller, and a DOM event listener.
Part 6: Using Stimulus in Rails Partials

In our Ruby on Rails partials, we use Stimulus to improve the user experience and control interaction with specific HTML elements. An example of this is adding a new post to a page without needing to reload the page.

To achieve this, we follow a simple process:

      1. First, create the partials file with the desired HTML code and integrate the necessary Stimulus controllers, actions, and targets.
      2. Then, define the corresponding Stimulus controller with the desired methods.
      3. Finally, test the functionality to ensure everything works as expected.

Conclusion and Outlook – Ruby on Rails

In this post, we explored using Stimulus in Rails partials and saw how it can improve the user experience. Stimulus provides a lightweight alternative to more extensive JavaScript frameworks and is particularly suitable for projects that don’t require complex client-side state management.

For future developments and experiments with Stimulus, there are numerous possibilities. We hope this post serves as a useful introduction to using Stimulus in Rails applications and encourages you to continue experimenting and building your own projects. Enhancing Interactivity: Integration Options for Stimulus in Ruby on Rails

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in:

centron Managed Cloud Hosting in Deutschland

How To Use Views in SQL

MySQL
How To Use Views in SQL Content1 Introduction2 Prerequisites for Using Views in SQL3 Connecting to MySQL and Setting up a Sample Database4 Understanding and Creating Views in SQL5 Changing…
centron Managed Cloud Hosting in Deutschland

How To Use Nested Queries in SQL

MySQL
How To Use Nested Queries in SQL Content1 Introduction2 Prerequisites for Nested Queries in SQL3 Connecting to MySQL and Setting up a Sample Database4 Using Nested Queries in SQL with…
centron Managed Cloud Hosting in Deutschland

How To Use Primary Keys in SQL

MySQL
How To Use Primary Keys in SQL Content1 Introduction2 Prerequisites for Understanding Primary Keys in SQL3 Connecting to MySQL and Setting up a Sample Database4 Introduction to Primary Keys in…