gpt4 book ai didi

ruby - 向现有模型添加单表继承 (STI)

转载 作者:行者123 更新时间:2023-11-29 13:26:46 26 4
gpt4 key购买 nike

我目前有多个非常相似的表。我可能应该用 STI 创建它们。

TypeOne < ActiveRecord::Base
TypeTwo < ActiveRecord::Base
TypeThree < ActiveRecord::Base

TypeOne(id: integer, parent_id: integer, created_at: datetime, updated_at: datetime)
TypeTwo(id: integer, parent_id: integer, created_at: datetime, updated_at: datetime)
TypeThree(id: integer, parent_id: integer, created_at: datetime, updated_at: datetime)

我现在正在尝试将 STI 添加到这些中。我创建了一个 BaseModel 并向该模型添加了一个类型。

BaseModel(id: integer, parent_id: integer, created_at: datetime, updated_at: datetime, type: string)

我还运行了一个迁移并向所有类型添加了一个类型列。

class AddTypeToTables < ActiveRecord::Migration
def change
add_column :type_ones, :type, :string
add_column :type_twos, :type, :string
add_column :type_threes, :type, :string
end
end

我想将所有类型表合并到一个 STI 中。模型中存在现有数据。如果我将它们合并到一个表中,我想各个表的 ID 会发生冲突。例如:

#<TypeOne id: 4, parent_id: 1, created_at: "2015-05-08 18:39:09", updated_at: "2015-09-07 19:42:03">

#<TypeTwo id: 4, parent_id: 1, created_at: "2015-04-08 17:48:59", updated_at: "2015-09-07 14:17:48">

如果我尝试使用 becomes,它似乎改变了类,但我找不到 BaseModel 中的记录

TypeOne.last.becomes!(BaseModel)
#<BaseModel id: 4, parent_id: 1, created_at: "2015-05-08 18:39:09", updated_at: "2015-09-07 19:42:03">

BaseModel.all
=> []

我也试过把继承表的type列改成basemodel

to = TypeOne.first
to.type = "BaseModel"
to.save

BaseModel.all
=> []

我试图将每个类更改为 BaseModel 的子类

TypeOne < BaseModel
TypeTwo < BaseModel
TypeThree < BaseModel

当我这样做时,我失去了与现有数据的连接,并且每个模型都显示为空。

如何合并现有表格?

最佳答案

当您用 PostgreSQL 标记它时,我将包括如何执行我在评论中建议的操作作为答案:

INSERT INTO base_model SELECT * FROM type_one ORDER BY id ASC;
INSERT INTO base_model SELECT * FROM type_two ORDER BY id ASC;
INSERT INTO base_model SELECT * FROM type_three ORDER BY id ASC;

要在生产数据集上安全地执行此操作,请将 SQL 放入 db/migrate 的迁移中(即在 db/migrate/20150907185938_integrate_tables.rb 之类的文件中)并首先在本地数据库上对其进行测试。这应该让你非常接近:

class IntegrateTables < ActiveRecord::Migration
def up
execute "INSERT INTO base_model SELECT * FROM type_one ORDER BY id ASC;"
execute "INSERT INTO base_model SELECT * FROM type_two ORDER BY id ASC;"
execute "INSERT INTO base_model SELECT * FROM type_three ORDER BY id ASC;"
end

def down
raise ActiveRecord::IrreversibleMigration, "It is unclear where original data stops and inserted data begins, can't migrate down"
end
end

如果对您有用,请将此答案标记为已接受 :)

关于ruby - 向现有模型添加单表继承 (STI),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32445539/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com