【问题标题】:How to customize rails orm generator如何自定义 rails orm 生成器
【发布时间】:2022-01-13 03:54:19
【问题描述】:

我想将 uuid 字段用于我正在生成的所有表,但想将 id 保留为主键。

我还想保留最少的代码,以便当 orm 生成器更改时,它会接收更改。

有什么想法吗?

【问题讨论】:

  • ORM 将数据库表映射到对象。因此,您必须使用迁移手动将 uuid 字段添加到数据库表中。如果该字段存在于表格中,它将自动在模型中可用。
  • 如果您只想要类中的字段而不是数据库中的字段,那么您可以创建一个继承自ActiveRecord::Base 的类并添加所需的字段,然后让您的所有模型都从该类继承。
  • 我想要它在数据库和模型中,但也想保留 id 字段。是的,我可以在迁移时手动添加它们,但如果 uuid 字段与 id 一起自动添加会更好

标签: ruby-on-rails generator


【解决方案1】:

你可以这样做:

创建迁移以将uuid 列添加到所有相关表。

class AddUUIDToTables < ActiveRecord::Migration
  add_column :table1, :uuid, :string
  add_column :table2, :uuid, :string
  ....
end

编写一个模块,在创建期间将uuid 设置为记录。

module Shared::UUIDable
  extend ActiveSupport::Concern

  included do  
    before_create { set_uuid }

    def set_uuid
      return if uuid.present?

      self.uuid = add_uuid_generation_logic
    end
  end
end

然后在所有相关模型中包含Shared::UUIDable 模块。 您将通过迁移或脚本为现有记录添加 uuid

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    • 2012-03-02
    • 1970-01-01
    • 2019-05-02
    • 2010-11-01
    • 2012-04-10
    • 2012-06-07
    相关资源
    最近更新 更多