【问题标题】:How to set default 'uuid-ossp' extension to all migration files using Rails?如何使用 Rails 为所有迁移文件设置默认的“uuid-ossp”扩展名?
【发布时间】:2014-06-19 05:23:59
【问题描述】:

如何为所有迁移文件设置默认的“uuid-ossp”扩展名?

enable_extension 'uuid-ossp'

我正在使用 Ruby 2.1、Rails 4 和 PostgreSQL。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 ruby-on-rails-3.2 rails-postgresql


    【解决方案1】:

    Rails 4 原生支持 Postgres 中的 UUID(通用唯一标识符)类型。在这里,我将描述如何使用它来生成UUIDs,而无需在 Rails 代码中手动生成。

    首先你需要启用Postgres扩展‘uuid-ossp’

    class CreateUuidPsqlExtension < ActiveRecord::Migration
      def self.up
        enable_extension "uuid-ossp"
      end
    
      def self.down
        disable_extension "uuid-ossp"
      end
    end
    

    您可以使用UUID 替换ID

    create_table :translations, id: :uuid do |t|
      t.string :title
      t.timestamps
    end
    

    在这种情况下,Translations 表将有一个 UUID 作为 ID,并且它是自动生成的。 Postgresq 中的 uuid-ossp 扩展有不同的算法来生成 UUID。 Rails 4 默认使用 v4。您可以在此处阅读有关这些算法的更多信息:http://www.postgresql.org/docs/current/static/uuid-ossp.html

    但是,有时您不希望将 UUID 作为 ID 替换,而是将其放在单独的列中:

    class AddUuidToModelsThatNeedIt < ActiveRecord::Migration
      def up
        add_column :translations, :uuid, :uuid
      end
    
      def down
        remove_column :translations, :uuid
      end
    end
    

    这将创建一个UUID 列,但不会自动生成 UUID。您必须在 Rails 中使用 SecureRandom 自己完成。但是,我们认为这是典型的数据库责任。幸运的是,add_column 中的默认选项有帮助:

    class AddUuidToModelsThatNeedIt < ActiveRecord::Migration
      def up
        add_column :translations, :uuid, :uuid, :default => "uuid_generate_v4()"
      end
    
      def down
        remove_column :translations, :uuid
      end
    end
    

    现在UUID 将被创建automatically,同样用于现有记录

    我希望这可以帮助您理解..如果这篇文章让您对 UUID 感到满意,那么请给这个答案投票... ;) 通过赫尔穆特

    【讨论】:

    • 我要求为所有迁移启用默认值
    【解决方案2】:

    要更改 Rails 生成的迁移,您可以modify the templates (follow the guide)。你要修改的模板是:active_record/migration/create_table_migration.rb

    另一方面,您也可以customize the config 使this generator 使用您想要的主键:

    config.generators do |g|
      g.primary_key_type             :uuid
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-27
      • 2013-06-05
      相关资源
      最近更新 更多