DEV Community

Germán Alberto Gimenez Silva
Germán Alberto Gimenez Silva

Posted on • Originally published at rubystacknews.com on

Enhancing the Trix Editor in Rails with AI-Powered Orthographic Correction

March 14, 2025

Introduction

When working with rich text editors in Ruby on Rails applications, enhancing usability is a key factor. Trix is a powerful WYSIWYG editor, but what if we could take it a step further by integrating AI-powered orthographic correction? In this article, I’ll walk you through how I built a feature that allows users to correct spelling and grammar mistakes in a Trix editor using DeepSeek AI.


Want to Add AI to Your Rails Project?

Do you need AI integration in your Rails project? Let’s work together to improve your application! Get in touch here .🚀


Prerequisites

Before diving into this integration, I highly recommend checking out these two articles:

  1. Streamline Your Ruby on Rails Development with Docker – This will help you set up a clean and containerized development environment.
  2. Enhancing the Trix Rich Text Editor in Ruby on Rails 8: A Custom Touch for a Better Experience! – This article covers Trix editor customization, which lays the foundation for our AI-powered feature.

Once you’re comfortable with these setups, we can move forward with integrating DeepSeek for orthographic correction.

Adding a Custom Button to the Trix Editor

Using StimulusJS, we can extend the Trix toolbar to include a new button for correcting orthography. Here’s how you can achieve this:

app/javascript/controllers/trix-controller.js

import { Controller } from "@hotwired/stimulus";

export default class extends Controller {
  connect() {
    addEventListener("trix-initialize", (event) => {
      const trixEditor = event.target;

      const aiButton = document.createElement("button");
      aiButton.setAttribute("type", "button");
      aiButton.setAttribute("title", "Correct Orthography");
      aiButton.classList.add("trix-button");
      aiButton.innerHTML = `
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
          <path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/>
        </svg>
      `;

      document.querySelector(".trix-button-group--text-tools").appendChild(aiButton);

      aiButton.addEventListener("click", () => {
        this.correctOrthography(trixEditor);
      });
    });
  }

  async correctOrthography(trixEditor) {
    try {
      const editor = trixEditor.editor;
      const content = editor.getDocument().toString();

      const response = await fetch("/orthography/correct", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ text: content }),
      });

      if (!response.ok) {
        throw new Error("Network response was not ok");
      }

      const result = await response.json();
      editor.loadHTML(result.corrected_text);
    } catch (error) {
      console.error("Error correcting orthography:", error);
      alert("An error occurred while correcting orthography.");
    }
  }
} 
Enter fullscreen mode Exit fullscreen mode

Backend: Creating the Orthography Correction API

Now, let’s create a controller to handle the correction requests by integrating DeepSeek AI.

app/controllers/orthography_controller.rb

class OrthographyController < ApplicationController
  skip_before_action :verify_authenticity_token

  def correct
    text = params.require(:text)
    corrected_text = call_ai_service(text)
    render json: { corrected_text: corrected_text }
  rescue StandardError => e
    Rails.logger.error("Orthography Correction Error: #{e.message}")
    render json: { error: "An error occurred while correcting orthography." }, status: :unprocessable_entity
  end

  private

  def call_ai_service(text)
    headers = {
      'Content-Type' => 'application/json',
      'Authorization' => "Bearer #{ENV['DEEPSEEK_API_KEY']}"
    }

    body = {
      model: "deepseek-chat",
      messages: [{ role: "user", content: "Correct this text: #{text}" }],
      temperature: 0.7,
      max_tokens: 500
    }.to_json

    response = Faraday.post(ENV['API_URL'], body, headers)

    if response.success?
      return JSON.parse(response.body)['choices'][0]['message']['content']
    else
      "Error: #{response.status} - #{response.body}"
    end
  end
end 
Enter fullscreen mode Exit fullscreen mode

config/routes.rb

post "orthography/correct", to: "orthography#correct" 
Enter fullscreen mode Exit fullscreen mode

Setting Up the Environment Variables

Since we’re using an external API, we need to store our API key securely. Add the following environment variables in your docker-compose.yml file:

docker-compose.yml
  rails:
    environment:
      - DEEPSEEK_API_KEY=<YOUR_API_KEY>
      - API_URL=https://api.deepseek.com/v1/chat/completions 
Enter fullscreen mode Exit fullscreen mode

🔗 Check Out the Full Code!

Explore the full implementation of AI-powered text correction in Trix on Rails.

👉

Conclusion

By following these steps, we’ve successfully integrated AI-powered orthographic correction into the Trix editor within a Rails application. This feature enhances the writing experience by providing users with real-time spelling and grammar corrections powered by DeepSeek.

If you’re looking to streamline your Rails development process, don’t forget to check out the prerequisite articles on Dockerizing Rails and enhancing the Trix editor. Together, these enhancements make for a more efficient and user-friendly application!

Would love to hear your thoughts—feel free to comment or share! 🚀

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay