# Build AI‑Powered Collaborative Docs in Rails Using the Univer Office SDK

> Step‑by‑step guide to embed the Univer Office SDK in a Rails app, adding AI‑enhanced document editing, real‑time collaboration, and secure file processing for

- URL: https://railsdev.io/blog/ai-collaborative-docs-rails-univer-sdk
- Published: 2026-11-16
- Author: Hendra Nicholas (Rails Full-Stack Developer & AI Engineer)

---

I’ve been building SaaS products with Rails since the early days of Rails 3, and embedding **Univer Office SDK Rails** support lets you run spreadsheets, rich‑text documents, and diagrams directly inside a Rails app with ActionCable sync and LLM hooks instead of farming users out to external tools.

Enter the [Univer Office SDK](https://github.com/dream-num/univer). It’s a JavaScript‑first, cloud‑agnostic library that gives you a full‑featured spreadsheet, rich‑text, and diagram editor that can be embedded in any web page. The SDK also ships with AI extension points—summarization, formula auto‑completion, smart‑style suggestions—that you can call from your own LLM endpoint. In this post I’ll walk you through how I wired the Univer Office SDK into a Rails 8.1 codebase, hooked up ActionCable for live collaboration, and layered an LLM‑backed “AI assistant” on top. The goal is to give you a concrete blueprint while being honest about the parts that are still experimental.

---

## Why AI‑Powered Collaborative Docs Matter for SaaS Teams

Before we dive into code, let’s make sure we agree on the problem we’re solving.

1. **Internal productivity** – Many SaaS teams still rely on Google Docs or Notion for design specs, data‑model sketches, and meeting notes.  Pulling that content into your own product forces a context switch and creates a security surface area.
2. **Customer‑facing collaboration** – If your product lets users co‑author contracts, reports, or dashboards, a native editor eliminates the “download‑edit‑upload” loop and lets you enforce business rules in real time.
3. **AI augmentation** – Modern LLMs can turn a half‑filled spreadsheet into a fully‑populated model, suggest chart types, or rewrite a paragraph for tone.  Embedding those capabilities directly where the user is typing feels magical and reduces friction.

The Univer Office SDK gives us the UI glue, while Rails gives us the backend glue (authentication, persistence, job processing).  The combination is surprisingly smooth, but it does surface a few trade‑offs:

* **Latency** – Real‑time syncing over WebSockets is cheap, but calling an LLM for every suggestion can add seconds of delay.  You’ll need to design a debounce strategy.
* **Data model fit** – Univer stores its document state as a binary “snapshot” (a base64‑encoded protobuf).  Mapping that into ActiveRecord or a JSONB column is straightforward, but you lose the ability to query the document’s interior structure without extra indexing.
* **Vendor lock‑in** – The SDK is open source, but the AI hooks are just HTTP endpoints you own.  If you ever want to replace the LLM, you can, but you’ll have to rewrite the integration layer.

With those caveats in mind, let’s get our hands dirty.

---

## Getting Started: Adding the Univer Office SDK to a Rails App

### 1. Install the JavaScript package

The SDK lives on npm under the name `@univerjs/core`.  I prefer using **Importmaps** for small SaaS apps, but if you already have Webpacker or esbuild in place, just add it as a regular dependency:

```bash
# Using Yarn (or npm)
yarn add @univerjs/core @univerjs/docs @univerjs/sheets @univerjs/design
```

If you’re on Rails 8 with importmap, you can pin the package directly:

```ruby
# config/importmap.rb
pin "@univerjs/core", to: "https://cdn.jsdelivr.net/npm/@univerjs/core@0.5.0/dist/index.js"
pin "@univerjs/docs", to: "https://cdn.jsdelivr.net/npm/@univerjs/docs@0.5.0/dist/index.js"
pin "@univerjs/sheets", to: "https://cdn.jsdelivr.net/npm/@univerjs/sheets@0.5.0/dist/index.js"
pin "@univerjs/design", to: "https://cdn.jsdelivr.net/npm/@univerjs/design@0.5.0/dist/index.js"
```

> **Verification note**  
> The exact CDN URLs and version numbers above are based on the current npm package at the time of writing; they may change with future releases.  Always check the official npm page for the latest stable version.

### 2. Create a Rails view that mounts the editor

Create a simple controller action and view.  The view loads the SDK, creates a container, and boots the editor with a blank document.

```erb
<!-- app/views/documents/edit.html.erb -->
<div id="univer-root" style="height: 80vh; border: 1px solid #ddd;"></div>

<%= javascript_include_tag "univer_editor", type: "module", defer: true %>
```

Now the JavaScript entry point:

```js
// app/javascript/univer_editor.js
import { Univer, UniverInstanceType } from "@univerjs/core";
import { DefaultTheme } from "@univerjs/design";
import { DocPlugin } from "@univerjs/docs";
import { SheetsPlugin } from "@univerjs/sheets";

document.addEventListener("DOMContentLoaded", () => {
  const univer = new Univer({
    theme: DefaultTheme,
    // You can pass a custom locale here if you need i18n
  });

  // Register the plugins you need (docs, sheets, charts, etc.)
  univer.registerPlugin(DocPlugin);
  univer.registerPlugin(SheetsPlugin);

  // Create a new document instance
  const doc = univer.createUnit(UniverInstanceType.UNIVER_DOC, {
    name: "Untitled",
    // The initial snapshot can be empty; we’ll load from the DB later
  });

  // Mount the UI
  const container = document.getElementById("univer-root");
  univer.mount(container);
});
```

That’s the minimal “Hello, Univer” you can get away with.  The next step is persisting the document state.

---

## Mapping Univer Snapshots to ActiveRecord

Univer serializes the whole workbook into a **snapshot** – essentially a JSON‑compatible object that can be stringified and stored.  In Rails we can treat it as a `text` column or, if you’re on PostgreSQL, a `jsonb` column for easier querying.

```ruby
# app/models/document.rb
class Document < ApplicationRecord
  belongs_to :user

  # The snapshot column holds the base64‑encoded protobuf (as a string)
  validates :snapshot, presence: true

  # Helper to deserialize into a Ruby hash (optional)
  def snapshot_hash
    JSON.parse(Base64.decode64(snapshot))
  rescue JSON::ParserError, ArgumentError
    {}
  end
end
```

Run a migration:

```bash
rails generate migration CreateDocuments user:references snapshot:text title:string
rails db:migrate
```

When the editor loads, we need to fetch the snapshot from the DB and feed it to Univer.  The SDK provides a `load` method on the document instance:

```js
// app/javascript/univer_editor.js (continued)
import { loadSnapshot } from "@univerjs/core";

async function loadDocument(documentId) {
  const resp = await fetch(`/documents/${documentId}/snapshot`);
  const { snapshot } = await resp.json(); // { snapshot: "base64..." }

  const decoded = atob(snapshot); // Convert base64 to binary string
  const json = JSON.parse(decoded);
  loadSnapshot(univer, json);
}

// Assuming the document ID is embedded in a data attribute
const docId = document.body.dataset.documentId;
if (docId) {
  loadDocument(docId);
}
```

And the corresponding Rails endpoint:

```ruby
# config/routes.rb
resources :documents, only: [:show, :update] do
  member do
    get :snapshot
    post :snapshot, to: "documents#save_snapshot"
  end
end
```

```ruby
# app/controllers/documents_controller.rb
class DocumentsController < ApplicationController
  before_action :authenticate_user!
  before_action :set_document, only: %i[show snapshot save_snapshot]

  def show
    # Renders edit.html.erb
  end

  def snapshot
    render json: { snapshot: @document.snapshot }
  end

  # Called by the client when the user clicks “Save”
  def save_snapshot
    @document.update!(snapshot: params[:snapshot])
    head :ok
  end

  private

  def set_document
    @document = current_user.documents.find(params[:id])
  end
end
```

> **Verification note**  
> The `loadSnapshot` function signature and usage are based on the SDK’s public API documentation as of the latest release.  If the SDK changes, you may need to adjust the import path or method name.

---

## Real‑Time Collaboration with ActionCable

Univer itself does not ship a collaboration engine, but its snapshot model is perfectly suited for **Operational Transform (OT)** or **CRDT** approaches.  For most SaaS use‑cases, a simple broadcast‑and‑merge strategy works fine, especially when you combine it with Rails’ built‑in ActionCable.

### 1. Define a channel

```ruby
# app/channels/document_channel.rb
class DocumentChannel < ApplicationCable::Channel
  def subscribed
    @document = Document.find(params[:document_id])
    stream_for @document
  end

  # Payload: { snapshot: "base64..." }
  def receive(data)
    # Persist the incoming snapshot (you could debounce this on the client)
    @document.update!(snapshot: data["snapshot"])
    # Broadcast to all other subscribers
    DocumentChannel.broadcast_to(@document, data)
  end
end
```

Add the route:

```ruby
# config/routes.rb
mount ActionCable.server => "/cable"
```

### 2. Wire the client

```js
// app/javascript/univer_editor.js (continued)
import consumer from "../channels/consumer";

function setupCable(documentId) {
  const cable = consumer.subscriptions.create(
    { channel: "DocumentChannel", document_id: documentId },
    {
      received(data) {
        // Another user sent a new snapshot – merge it locally
        const decoded = atob(data.snapshot);
        const json = JSON.parse(decoded);
        loadSnapshot(univer, json);
      },

      // Optional: send our own snapshot every few seconds
      sendSnapshot() {
        const snapshot = univer.getSnapshot(); // hypothetical API
        const encoded = btoa(JSON.stringify(snapshot));
        this.perform("receive", { snapshot: encoded });
      },
    }
  );

  // Debounce sending to avoid flooding the server
  setInterval(() => cable.sendSnapshot(), 3000);
}

// Kick off after the document loads
if (docId) {
  setupCable(docId);
}
```

> **Verification note**  
> The `univer.getSnapshot()` method is illustrative; the actual SDK may expose a different accessor for the current document state.  Consult the SDK’s API reference for the exact call.

With this in place, any user who edits the document will see updates within a few seconds.  For tighter latency you can push changes on every keystroke, but that quickly becomes bandwidth‑heavy and requires a true CRDT implementation, which is beyond the scope of this article.

---

## Adding an AI Assistant: Summarize, Auto‑Complete, and Smart Formatting

Now that we have a live editor, let’s sprinkle some AI on top.  The pattern I use is:

1. **Client‑side trigger** – a button or slash command (`/summarize`) that sends the current document text to a backend endpoint.
2. **Backend LLM call** – a service object that talks to OpenAI, Anthropic, or a self‑hosted Llama.cpp instance.
3. **Patch the document** – the response is turned into a Univer patch (e.g., insert text, replace a range) and applied via the SDK.

### 1. Expose a minimal API

```ruby
# config/routes.rb
post "documents/:id/ai/summarize", to: "documents#summarize"
post "documents/:id/ai/auto_complete", to: "documents#auto_complete"
```

```ruby
# app/controllers/documents_controller.rb (excerpt)
class DocumentsController < ApplicationController
  # ...

  def summarize
    text = extract_text(@document.snapshot)
    summary = AiAssistant.summarize(text)
    render json: { summary: }
  end

  def auto_complete
    prefix = params[:prefix] # the text the user typed so far
    suggestion = AiAssistant.auto_complete(prefix)
    render json: { suggestion: }
  end

  private

  # Very naive extraction – you’ll probably want a proper parser for sheets vs docs
  def extract_text(snapshot_base64)
    json = JSON.parse(Base64.decode64(snapshot_base64))
    # Traverse the JSON to pull out plain text nodes
    # For brevity, we just join all string values
    json.values.select { |v| v.is_a?(String) }.join("\n")
  end
end
```

### 2. The service object that talks to the LLM

```ruby
# app/services/ai_assistant.rb
class AiAssistant
  OPENAI_ENDPOINT = "https://api.openai.com/v1/chat/completions".freeze

  def self.summarize(text)
    payload = {
      model: "gpt-4o-mini",
      messages: [{ role: "user", content: "Summarize the following document in 3 bullet points:\n\n#{text}" }],
      temperature: 0.2
    }

    response = http_post(payload)
    response.dig("choices", 0, "message", "content")
  end

  def self.auto_complete(prefix)
    payload = {
      model: "gpt-4o-mini",
      messages: [{ role: "user", content: "Continue this sentence:\n\n#{prefix}" }],
      max_tokens: 30,
      temperature: 0.7
    }

    response = http_post(payload)
    response.dig("choices", 0, "message", "content")
  end

  def self.http_post(body)
    conn = Faraday.new(url: OPENAI_ENDPOINT) do |f|
      f.request :json
      f.response :json, content_type: /\bjson$/
      f.adapter Faraday.default_adapter
    end

    conn.post do |req|
      req.headers["Authorization"] = "Bearer #{ENV.fetch("OPENAI_API_KEY")}"
      req.body = body
    end.body
  end
end
```

> **Verification note**  
> The OpenAI endpoint and request format follow the official API documentation as of 2024‑04‑01.  If you use a different provider, adjust the payload accordingly.

### 3. Hook the UI

Add a tiny toolbar to the editor.  Univer lets you inject custom React components, but for a quick demo we’ll just use plain HTML and attach listeners.

```erb
<!-- app/views/documents/edit.html.erb (add below the root div) -->
<div class="univer-toolbar" style="margin-top: 0.5rem;">
  <button id="ai-summarize">Summarize</button>
  <button id="ai-auto-complete">Auto‑Complete</button>
</div>
```

```js
// app/javascript/univer_editor.js (continued)
document.getElementById("ai-summarize").addEventListener("click", async () => {
  const snapshot = univer.getSnapshot(); // hypothetical
  const encoded = btoa(JSON.stringify(snapshot));
  const resp = await fetch(`/documents/${docId}/ai/summarize`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ snapshot: encoded })
  });
  const { summary } = await resp.json();
  alert("AI Summary:\n" + summary);
});

document.getElementById("ai-auto-complete").addEventListener("click", async () => {
  const selection = univer.getSelection(); // hypothetical API
  const prefix = selection?.text || "";
  const resp = await fetch(`/documents/${docId}/ai/auto_complete`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ prefix })
  });
  const { suggestion } = await resp.json();
  // Insert suggestion at cursor
  univer.applyPatch({ insert: suggestion, at: selection?.range?.end });
});
```

That’s a minimal “AI assistant” you can iterate on.  In production you’ll want:

* **Rate limiting** – guard against runaway LLM calls.
* **Caching** – store recent summaries to avoid recomputation.
* **User‑level preferences** – let users toggle AI features on/off.

---

## Security, Permissions, and Auditing

Embedding a powerful editor that can run arbitrary formulas or embed images opens a surface area you need to police.

### 1. Scope the snapshot per user

Never expose a document’s snapshot to a user who isn’t authorized.  The `DocumentsController` already scopes to `current_user.documents`, but if you have team‑based sharing you’ll need a more granular policy, perhaps using Pundit:

```ruby
# app/policies/document_policy.rb
class DocumentPolicy < ApplicationPolicy
  def show?
    record.owner == user || record.shared_with?(user)
  end

  def update?
    show?
  end
end
```

### 2. Sanitize incoming AI content

LLMs can hallucinate HTML or script tags.  Before applying any AI‑generated text to the document, run it through Rails’ built‑in sanitizer:

```ruby
sanitized = ActionController::Base.helpers.sanitize(ai_output, tags: %w[b i strong em u])
```

### 3. Audit trail

For compliance (e.g., GDPR or SOC2) you may need to retain a history of changes.  One approach is to version the snapshot on every save:

```ruby
# app/models/document.rb
has_many :document_versions, dependent: :destroy

def save_snapshot!(new_snapshot)
  transaction do
    document_versions.create!(snapshot: snapshot, saved_at: Time.current)
    update!(snapshot: new_snapshot)
  end
end
```

You can then expose an endpoint to retrieve past versions, or feed them into a diff viewer.

---

## Testing the Integration

Testing a UI‑heavy component like Univer can feel daunting, but you can get decent coverage with a mix of unit, integration, and system tests.

### 1. Model tests – snapshot round‑trip

```ruby
# spec/models/document_spec.rb
require "rails_helper"

RSpec.describe Document, type: :model do
  it "stores and retrieves a valid snapshot" do
    raw = { sheets: [{ name: "Sheet1", data: [] }] }
    encoded = Base64.encode64(JSON.dump(raw))
    doc = Document.create!(user: create(:user), snapshot: encoded, title: "Test")
    expect(doc.snapshot_hash).to eq(raw.stringify_keys)
  end
end
```

### 2. Controller tests – AI endpoints

```ruby
# spec/requests/documents_ai_spec.rb
require "rails_helper"

RSpec.describe "Documents AI", type: :request do
  let(:user) { create(:user) }
  let(:doc) { create(:document, user: user, snapshot: Base64.encode64("{}")) }

  before { sign_in(user) }

  it "returns a summary" do
    allow(AiAssistant).to receive(:summarize).and_return("• Point A\n• Point B")
    post summarize_document_path(doc), params: {}
    expect(response).to have_http_status(:ok)
    expect(JSON.parse(response.body)["summary"]).to include("Point A")
  end
end
```

### 3. System tests – real‑time collaboration

Rails 8 ships with **Turbo‑Stream** and **Capybara** that can drive multiple browser sessions.  Here’s a skeleton:

```ruby
# spec/system/collaboration_spec.rb
require "rails_helper"

RSpec.describe "Collaborative editing", type: :system, js: true do
  let(:user_a) { create(:user) }
  let(:user_b) { create(:user) }
  let(:doc) { create(:document, user: user_a, snapshot: Base64.encode64("{}")) }

  it "syncs changes across sessions" do
    # Session A
    using_session(:a) do
      sign_in(user_a)
      visit edit_document_path(doc)
    end

    # Session B
    using_session(:b) do
      sign_in(user_b)
      visit edit_document_path(doc)
    end

    # Simulate a change in session A
    using_session(:a) do
      find("#univer-root").send_keys("Hello from A")
      # Trigger a manual save to fire the ActionCable broadcast
      click_button "Save"
    end

    # Verify session B receives the update
    using_session(:b) do
      expect(page).to have_content("Hello from A")
    end
  end
end
```

> **Verification note**  
> The exact selectors (`#univer-root`, “Save” button) depend on how you implement the UI; the test is illustrative of the pattern rather than a copy‑paste script.

---

## Deployment Considerations

### 1. Asset delivery

If you’re using importmap, the SDK assets are fetched from a CDN at runtime, which simplifies deployment but adds a third‑party dependency.  For tighter control you can pre‑bundle the SDK with **esbuild** and serve it from your own CDN or S3 bucket.

### 2. Scaling ActionCable

Real‑time collaboration can generate a lot of WebSocket traffic.  In production I run ActionCable behind **Redis** (the default) and horizontally scale the cable workers using **Kamal** (see the official guide for Rails 8: https://github.com/basecamp/kamal).  Make sure you configure `cable.yml` with a production Redis URL and enable `allowed_request_origins`.

```yaml
# config/cable.yml
production:
  adapter: redis
  url: <%= ENV.fetch("REDIS_URL") %>
  channel_prefix: myapp_production
```

### 3. LLM cost management

LLM calls can quickly balloon your bill.  Some practical mitigations:

* **Cache per‑document summaries** for 24 hours.
* **Throttle auto‑complete** to one request per 5 seconds per user.
* **Batch updates** – instead of sending a snapshot on every keystroke, send only when the user pauses.

You can also swap the OpenAI endpoint for a self‑hosted model (e.g., Ollama) to gain predictable pricing, but then you’ll need to provision GPU resources.

---

## Lessons Learned & Areas of Uncertainty

1. **Snapshot size matters** – A fully‑fledged spreadsheet with thousands of rows can push the snapshot into the megabyte range.  Storing that in a single `text` column works, but you’ll see slower DB reads/writes.  I’ve started experimenting with **pgvector** to store a compressed representation, but the trade‑off between queryability and size is still fuzzy.  If your SaaS expects massive workbooks, consider a separate blob store (e.g., S3) and keep only a reference ID in the DB.
2. **Conflict resolution** – The naïve broadcast‑and‑replace approach works for low‑contention editing (e.g., a single author or occasional co‑author).  When you have many simultaneous editors, you’ll see “last write wins” anomalies.  Implementing a true CRDT is non‑trivial; the Univer community is discussing a built‑in solution, but it’s not production‑ready yet.  Until then, I recommend adding a “Lock for editing” button that temporarily disables broadcasting for a user.
3. **AI latency** – Even with a 200 ms network round‑trip, the LLM inference can take 1–2 seconds.  Users notice the lag, especially on mobile.  My current workaround is to show a spinner and pre‑fetch suggestions as the user types, but the UX is still a work in progress.  Future versions of the SDK may expose streaming token APIs that let you display partial completions in real time.
4. **Browser compatibility** – The SDK uses modern ES2022 features (e.g., `BigInt`, `structuredClone`).  All evergreen browsers are fine, but legacy IE11 support is dead.  If you have a corporate audience with older browsers, you’ll need a polyfill strategy or a fallback to a simpler editor.

---

## Wrapping Up

Embedding the **Univer Office SDK** into a Rails app gives you a powerful, extensible canvas for collaborative documents, and the Rails stack provides all the glue you need to make it persistent, real‑time, and AI‑augmented.  The steps boil down to:

1. **Add the SDK** via npm or importmap.  
2. **Persist snapshots** in a `text` or `jsonb` column.  
3. **Broadcast changes** with ActionCable (or a more sophisticated CRDT later).  
4. **Layer AI** by exposing thin controller endpoints that call your LLM of choice.  
5. **Secure and audit** the flow, especially if you allow formula execution or external embeds.  
6. **Test** at the model, controller, and system levels to catch regressions early.

If you’re already experimenting with AI agents in your UI, you’ll find the patterns here dovetail nicely with the [AG‑UI Protocol](/blog/ag-ui-protocol-for-rails-apps) and [Agent Skills for Rails](/blog/agent-skills-for-rails). The biggest unknown right now is how the community will converge on a standard collaboration protocol for [Univer](https://docs.univer.ai/); keep an eye on the GitHub repo and be ready to swap the broadcast layer when a more robust solution lands.

## Frequently asked questions

### How does Rails store Univer Office SDK documents?

Univer serializes workbooks and documents as JSON or binary snapshots, which fit naturally in a PostgreSQL `jsonb` column for moderate files or Active Storage / S3 with a DB reference key when snapshots grow into megabytes.

### Is ActionCable enough for collaborative editing?

ActionCable works well for low-contention editing and presence indicators, but heavy simultaneous editing on the same sheet needs a CRDT or explicit edit-locking to prevent last-write-wins overwrites.

### How do I keep LLM costs under control inside a live document editor?

Debounce AI suggestion requests, cache summaries per document version, and move batch transforms into background jobs rather than firing an LLM call on every keystroke.

## Conclusion

Embedding the Univer Office SDK into a Rails application gives your SaaS native spreadsheets and documents backed by your existing authentication, ActionCable channels, and LLM endpoints.

If you’re building collaborative AI features into a Rails product, explore my [AI software development services](/services/ai-software-development) or [book a discovery call](/#contact).
