Rails Insights

How to Develop Applications Fast with Rails and HTMX

In the fast-paced world of web development, speed and efficiency are paramount. Ruby on Rails (often simply referred to as Rails) is a powerful web application framework that allows developers to build applications quickly and effectively. When combined with HTMX, a library that enables you to access modern browser features directly from HTML, you can create dynamic, responsive applications with minimal effort. In this article, we will explore how to leverage Rails and HTMX to accelerate your application development process.

What is Ruby on Rails?

Ruby on Rails is an open-source web application framework written in Ruby. It follows the convention over configuration (CoC) and the DRY (Don't Repeat Yourself) principles, which help developers write less code while accomplishing more. Rails is particularly well-suited for building database-backed web applications and provides a rich set of tools and libraries to streamline the development process.

What is HTMX?

HTMX is a lightweight JavaScript library that allows you to create dynamic web applications by extending HTML with additional attributes. It enables you to make AJAX requests, swap HTML content, and handle events without writing extensive JavaScript code. This makes it an excellent companion for Rails, as it allows you to enhance your Rails applications with interactivity while keeping your codebase clean and maintainable.

Getting Started with Rails and HTMX

Before we dive into the specifics of using Rails and HTMX together, let’s set up a simple Rails application. If you haven’t already, make sure you have Ruby and Rails installed on your machine. You can create a new Rails application by running the following command:

rails new htmx_rails_app
cd htmx_rails_app

Next, we need to add HTMX to our application. You can do this by including the HTMX library in your application layout. Open the file app/views/layouts/application.html.erb and add the following line within the <head> section:

<%= javascript_include_tag 'https://unpkg.com/htmx.org@1.9.3' %>

Now that we have HTMX set up, let’s create a simple application that allows users to manage a list of tasks.

Creating a Simple Task Manager

Step 1: Generate the Task Model

First, we need to create a Task model. Run the following command to generate the model and the corresponding migration:

rails generate model Task title:string completed:boolean
rails db:migrate

Step 2: Set Up the Controller

Next, we’ll create a controller to handle our tasks. Run the following command:

rails generate controller Tasks

Now, open the newly created controller file app/controllers/tasks_controller.rb and add the following code:

class TasksController < ApplicationController
  def index
    @tasks = Task.all
    @task = Task.new
  end

  def create
    @task = Task.new(task_params)
    if @task.save
      render partial: 'task', locals: { task: @task }
    else
      render json: { error: @task.errors.full_messages }, status: :unprocessable_entity
    end
  end

  private

  def task_params
    params.require(:task).permit(:title, :completed)
  end
end

Step 3: Create the Views

Now, let’s create the views for our tasks. First, create a new file app/views/tasks/index.html.erb and add the following code:

<h1>Task Manager</h1>

<div id="task-list">
  <%= render @tasks >
</div>

<%= form_with model: @task, local: false do |form| %>
  <%= form.text_field :title, placeholder: "New Task" %>
  <%= form.submit "Add Task" %>
<% end %>

Next, create a partial view for rendering individual tasks. Create a new file app/views/tasks/_task.html.erb and add the following code:

<div class="task">
  <span><%= task.title %></span>
  <span>Completed: <%= task.completed? %></span>
</div>

Step 4: Add HTMX Attributes

To make our form work with HTMX, we need to add some attributes to the form. Update the form in app/views/tasks/index.html.erb as follows:

<%= form_with model: @task, local: false, html: { 'hx-post': tasks_path, 'hx-target': '#task-list', 'hx-swap': 'beforeend' } do |form| %>
  <%= form.text_field :title, placeholder: "New Task" %>
  <%= form.submit "Add Task" %>
<% end %>

Here, we are using HTMX attributes to specify that when the form is submitted, it should send a POST request to the tasks_path, and the response should be inserted into the #task-list div.

Running the Application

Now that we have everything set up, let’s run our application. Start the Rails server by running:

rails server

Open your browser and navigate to http://localhost:3000/tasks. You should see your task manager application. You can add tasks, and they will appear dynamically without a full page reload, thanks to HTMX!

Benefits of Using Rails with HTMX

Combining Rails with HTMX offers several advantages:

  • Speed of Development: Rails provides a robust framework for building applications quickly, while HTMX allows you to add interactivity without writing extensive JavaScript.
  • Cleaner Code: By using HTMX, you can keep your JavaScript to a minimum, resulting in a cleaner and more maintainable codebase.
  • Enhanced User Experience: HTMX enables you to create a more dynamic and responsive user experience, making your applications feel faster and more engaging.
  • Less Context Switching: With HTMX, you can handle most of your interactivity directly in your HTML, reducing the need to switch between different files and contexts.

Conclusion

In this article, we explored how to develop applications quickly using Ruby on Rails and HTMX. By leveraging the strengths of both technologies, you can create dynamic, responsive applications with minimal effort. Whether you are building a simple task manager or a more complex application, Rails and HTMX can help you streamline your development process and enhance the user experience. So why not give it a try? Happy coding!

Published: August 22, 2024

© 2024 RailsInsights. All rights reserved.