Rails | Foreign Key Constraint On Unique Column Other Than ID?

  Kiến thức lập trình

I have a table of tenants. While tenants do have an id, they also have a code column that is unique and indexed as well. The code column value has the advantage of being human readable. As such, I would like to use it when creating a foreign-key constraint on various other tables. However, I haven’t had much luck googling how to implement this so far.

For instance, I attempted the following in a migration for adding a new table:

class CreateApps < ActiveRecord::Migration[7.1]
  def change
    create_table :apps, id: :uuid do |t|
      ...
      t.references :tenant_code, type: :string, index: true, foreign_key: { to_table: :tenants }
      ...
    end
 end
end

Unfortunately, when I attempt to run this migration I get an error like this:

PG::DatatypeMismatch: ERROR: foreign key constraint “fk_rails_899289dfd2” cannot be implemented DETAIL: Key columns “tenant_code_id” and “id” are of incompatible types: character varying and uuid.

Rails wants to append _id to whatever column name I specify here rather than just using tenant_code, and it attempts to link it to the tenants table’s id column rather than the code column…

How can I get Rails to create the apps table with a tenant_code column that serves as a foreign key to the tenants table via its code column?

LEAVE A COMMENT