2009-02-08 43 views
4

我正在尝试为仅用作枚举的简单表创建迁移。所以我想立即用它的值填充表格。我试过如下:在迁移中填充Rails类

class CreateUserTypes < ActiveRecord::Migration 

def self.up 
    create_table :user_types do |t| 
     t.column :type, :string 
     t.timestamps 
    end 
    end 

    def self.down 
    drop_table :user_types 
    end 

    UserType.create :type => "System administrator" 
    UserType.create :type => "Simulation controller" 
end 

,但我得到这个错误:

rake aborted! 
An error has occurred, all later migrations canceled: 

Could not find table 'user_types' 

我是继Rails wiki和预期它的工作。


谢谢。但是你的建议似乎并不奏效。那么,我看不到弦。

sqlite> select * from user_types; 
1||2009-02-08 12:00:56|2009-02-08 12:00:56 
2||2009-02-08 12:00:57|2009-02-08 12:00:57 

回答

3

这已经给出了两个答案的组合,但是这应该为你工作:

class CreateUserRoles < ActiveRecord::Migration 
    def self.up 
    create_table :user_roles do |t| 
     t.string :role 
     t.timestamps 
    end 

    UserRole.create :role => "System administrator" 
    UserRole.create :role => "Simulation controller" 
    end 

    def self.down 
    drop_table :user_roles 
    end 
end 

重命名你的类用户类型来的UserRole(与相关的测试类放在一起,假设你使用创建的所有的这些发电机)。 Rails对单表继承使用'type'列,并且当你有从基类派生的模型时,它会自动用类名填充该字段。

1

试试这个

class CreateUserTypes < ActiveRecord::Migration 

    def self.up 
    create_table :user_types do |t| 
     t.string :role 
     t.timestamps 
    end 

    UserType.create :role => "System administrator" 
    UserType.create :role => "Simulation controller" 
    end 

    def self.down 
    drop_table :user_types 
    end 

end 

这是在默认情况下,当你调用耙分贝运行self.up方法中:迁移

编辑:改列名“角色”作为“类型'保留给单表继承。 (看评论)。对Kyle Boon道歉最后得到一个非常相似的答案。

+0

下一个问题:什么我必须这样做耙分贝:迁移在更改迁移文件后,将更新数据库。耙子看起来不像C那样工作。 – alamodey 2009-02-08 11:08:24

+0

每个迁移文件都按顺序运行。如果您更改了迁移文件,则应该回滚到该版本并重新运行。或者,您可以编写进一步的迁移文件,以便在原始文件上进行所需的更改。 – DanSingerman 2009-02-08 11:25:33

0

HermanD的答案应该可行。但我想指出,你应该小心使用名为'type'的AFAIK列,Rails使用STI的列名。

1

一点题外话,但值得一提的是:它被认为是拙劣的形式来实例化在迁移数据,因为“官方”的方式来创建生产环境中的数据库是

rake db:schema:load 

这当然不会加载来自迁移文件的数据。你可能想看看我最喜欢的插件之一:Seed_Fu。

随着Seed_fu,您创建YAML数据固定装置,然后发出

rake db:seed 

当你想要得到的数据建立。

0
  1. 广场内 self.up
  2. 呼叫UserType.reset_column_information 创建语句创建表后填充它 之前。在创建表之前加载模型UserType为 ,因此在 表存在之前, rails已收集有关数据库结构的信息 。您需要重置 它,因此Rails将再次检查表 属性。
  3. 不要使用'type'作为属性名称。它用于STI。

    类CreateUserTypes <的ActiveRecord ::迁移

    def self.up 
        create_table :user_types do |t| 
        t.column :role, :string 
        t.timestamps 
        end 
    
        UserType.reset_column_information 
    
        UserType.create :role => "System administrator" 
        UserType.create :role => "Simulation controller" 
    
    end 
    
    def self.down 
        drop_table :user_types 
    end