Search code examples
ruby-on-railspostgresqlrubygemsuuidglobalize

Ruby on Rails 4.2 with Globalize gem for UUID table


I use Globalize gem for my rails 4.2 project, and the table primary ID is UUID in postgre.

Here is the table migration codes and created translation table foreign key is integer type, not UUID.

class CreateMessageThreads < ActiveRecord::Migration
  def up

    enable_extension 'uuid-ossp'

    create_table :message_threads, id: :uuid do |t|
      t.integer :resource_id, null: false
      t.string :resource_type, null: false
      t.datetime :deleted_at

      t.timestamps null: false
    end

    MessageThread.create_translation_table!({
      :title => :string
    })

  end

  def down
    drop_table :message_threads
    MessageThread.drop_translation_table!
  end
end

Is there a way to make this UUID work??

cheers


Solution

  • I was not able to use the hardcoded solution provided by Thomas Engelbrecht because not all my models use uuid.

    Since the model is delegated we can check it's primary key type by adding a method :

    def primary_key_type
        column_type(model.primary_key).to_sym
    end
    

    And i'm using Rails 4.2 so I can use the references type option ( source )

    module Globalize
      module ActiveRecord
        module Migration
          class Migrator
            def primary_key_type
              column_type(model.primary_key).to_sym
            end
    
            def create_translation_table
              connection.create_table(translations_table_name, id: primary_key_type) do |t|
                t.references table_name.sub(/^#{table_name_prefix}/, '').singularize, null: false, type: primary_key_type
                t.string :locale, null: false
                t.timestamps null: false
              end
            end
          end
        end
      end
    end
    

    There must be a cleaner way, but I lack the experience to create a pull request.