Skip to content

[BUG] rails generate ruby_llm:install migrations fails due to references to non-existent tables #409

@matiasmoya

Description

@matiasmoya

Basic checks

  • I searched existing issues - this hasn't been reported
  • I can reproduce this consistently
  • This is a RubyLLM bug, not my application code

What's broken?

The rails generate ruby_llm:install generator creates migrations with foreign key references to tables that haven't been created yet, causing migration failures.

How to reproduce

  1. Create a new rails app
  2. bundle add ruby_llm
  3. bundle install
  4. rails db:create db:migrate
  5. rails generate ruby_llm:install
  6. rails db:migrate

Expected behavior

Migrations should run successfully, creating all necessary tables and relationships.

What actually happened

The generated migrations contain t.references calls that reference tables (like models) that are created in later migrations. The migration attempts to create foreign key constraints to tables that don't exist yet.

❯ rails db:migrate
== 20250912205042 CreateChats: migrating ======================================
-- create_table(:chats)
bin/rails aborted!
StandardError: An error has occurred, this and all later migrations canceled: (StandardError)

PG::UndefinedTable: ERROR:  relation "models" does not exist
/home/user/code/rubyllm-bug-repro/db/migrate/20250912205042_create_chats.rb:3:in 'CreateChats#change'

Caused by:
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "models" does not exist (ActiveRecord::StatementInvalid)
/home/user/code/rubyllm-bug-repro/db/migrate/20250912205042_create_chats.rb:3:in 'CreateChats#change'

Caused by:
PG::UndefinedTable: ERROR:  relation "models" does not exist (PG::UndefinedTable)
/home/user/code/rubyllm-bug-repro/db/migrate/20250912205042_create_chats.rb:3:in 'CreateChats#change'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

Workaround:

  1. Remove the t.references lines from the initial table creation migrations
  2. Create a separate migration after all tables are created to add the foreign key references:
    rails generate migration add_references_to_chats_tool_calls_and_messages
class AddReferencesToChatsToolCallsAndMessages < ActiveRecord::Migration[8.1]
  def change
    add_reference :chats, :model, foreign_key: true
    add_reference :tool_calls, :message, null: false, foreign_key: true
    add_reference :messages, :chat, null: false, foreign_key: true
    add_reference :messages, :model, foreign_key: true
    add_reference :messages, :tool_call, foreign_key: true
  end
end

Environment

  • Ruby version: ruby 3.4.5
  • RubyLLM version: 1.7.1
  • OS: Linux
  • postgres (PostgreSQL) 17.6

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions