2009-11-09 16 views
0

如果我的模式是这样的:可能使用ActiveRecord :: Migration的基类吗?

(app/models/letter.rb) 
class Letter < ActiveRecord::Base 
    def cyrilic_equivilent 
    # return somethign similar 
    end 
end 

class A < Letter 
end 

class B < Letter 
end 

可以将我的移民活动也遵循这个模式:

class CreateLetter < ActiveRecord::Migration 
    def self.up 
    create_table :letters do |t| 
     t.timestamps 
    end 
    end 
end 

class CreateA < CreateLetter 
end 

class CreateB < CreateLetter 
end 

回答

1

你正在试图做的不会在所有的工作是什么。

运行迁移时,Rails运行up类方法。让新的迁移继承另一个迁移的up方法将尝试两次创建相同的表。这将导致迁移失败。

这不是什么问题。由于迁移工作的方式,Rails将只运行与包含它的文件共享其名称的类。

看起来你正在试图做两件类似的事情之一。

  1. 模型建议单表继承。 STI需要一个名为type的字符串列,并且所有的子类都将使用父模型的表格,在这种情况下是字母。你只需要定义一个表,并且Rails在声明一个模型成为另一个模型的子类时会处理所有类型的列奥秘。

  2. 您试图定义多个相似的表格,然后调整差异。这可以通过单个迁移中的循环和条件来完成。但是,您需要在任何继承其他模型的模型中定义table_name以禁用隐含的单表继承。迁移回路想是这样的:

    class CreateLetter < ActiveRecord::Migration 
        def self.up 
        [:letters, :a, :b].each do |table_name| 
         create_table table_name do |t| 
         ... 
         t.timestamps 
    
         if table_name == :a 
          # columns only in table a 
         end 
    
         if table_name == :b 
          # columns only in table b 
         end   
         end 
        end 
    end 
    
1

当然可以......什么这是你的目标是什么?您将需要申报

class CreateA < CreateLetter

1

我在ActiveRecord的3.0.3

class BaseMigration < ActiveRecord::Migration 
    def self.create_base_columns(tbl) 
    tbl.string :some_reused_field 
    end 
end 

class AnotherMigration < BaseMigration 
    def self.up 
    create_table(:sometable) do |t| 
    create_base_columns(t) 
    end 
end 

与迁移这样更新到3.2.3我不断收到后“失踪方法:create_table',所以我不得不改变:

module BaseMigration 
    def create_base_columns(tbl) 
    tbl.string :some_reused_field 
    end 
end 

class AnotherMigration < ActiveRecord::Migration 
    extend BaseMigration 
    def self.up 
    create_table(:sometable) do |t| 
     create_base_columns(t) 
    end 
    end 
end 

我会假设这些是等价的,但由于某种原因AR不再让我使用继承。

注:确实工作在3.0.3但只延长模块两种方法对3.2.3

工作时,我有时间,我想试试这一个准系统Rails应用程序。

相关问题