2009-05-19 77 views
1

我创建了以Posts表定义开始的迁移数。在Rails迁移中加载数据

class CreatePosts < ActiveRecord::Migration 
    def self.up 
    create_table :posts do |t| 
     t.column "title", :string, :limit => 100, :default => "", :null => false 
     t.column "content", :text, :null => false 
     t.column "author", :string, :limit => 100, :default => 0, :null => false 
     t.column "category", :string, :limit => 20, :default => "", :null => false 
     t.column "status", :string, :limit => 20, :default => "", :null => false 
     t.timestamps 
    end 
    end 

    def self.down 
    drop_table :posts 
    end 
end 

,另一个用于一个用户表中,我创建表后,加载默认的用户的一些数据。

class CreateUsers < ActiveRecord::Migration 
    def self.up 
    create_table :users do |t| 
     t.column "username", :string,  :limit => 25, :default => "", :null => false 
     t.column "hashed_password", :string, :limit => 40, :default => "", :null => false 
     t.column "first_name", :string, :limit => 25, :default => "", :null => false 
     t.column "last_name", :string, :limit => 40, :default => "", :null => false 
     t.column "email", :string,  :limit => 50, :default => "", :null => false 
     t.column "display_name", :string, :limit => 25, :default => "", :null => false 
     t.column "user_level", :integer, :limit => 3, :default => 0, :null => false 
     t.timestamps 
    end 
    user = User.create(:username => 'bopeep', 
     :hashed_password => 'bopeep', 
     :first_name => 'Bo', 
     :last_name => 'Peep', 
     :email => '[email protected]', 
     :display_name => 'Little Bo Peep', 
     :user_level => 9) 
    end 

    def self.down 
    drop_table :users 
    end 
end 

接下来,我创建了一个迁移来更改Posts表以将表重命名为blog_posts。在这里我也想加载一个默认的博客文章条目。

class AlterPosts < ActiveRecord::Migration 
    def self.up 
    rename_table :posts, :blog_posts 
    change_column :blog_posts, :author, :integer, :default => 0, :null => false 
    rename_column :blog_posts, :author, :author_id 
    add_index :blog_posts, :author_id 
    bopeep = User.find_by_username 'bopeep' 
    BlogPost.create(:title => 'test', :content => 'test', :author_id => bopeep.id, :category => 'test', :status => 'ok') 
    end 

    def self.down 
    remove_index :blog_posts, :author_id 
    rename_table :blog_posts, :posts 
    rename_column :posts, :author_id, :author 
    change_column :posts, :author, :string, :limit => 100, :default => 0, :null => false 
    end 
end 

但是,这会产生错误:

uninitialized constant AlterPosts::BlogPost 

我应该如何已加载默认的博文,而不是 “BlogPost.create”?

回答

5

将您的rename_table和您的更改/重命名列迁移到另一个迁移文件。

我不认为重命名是在整个块经过之后才提交的,所以blog_posts还不存在。

+0

你的解释很有道理。我做了你所说的并创建了一个LoadDefaultData迁移文件,该文件在其他所有内容之后启动。但是我得到一个错误:“BlogPost.create”的“未初始化的常量LoadDefaultData :: BlogPost”。这个文件与上面列出的代码相同:bopeep = User.find_by_username'bopeep' BlogPost.create(:title =>'test',:content =>'test',:author_id => bopeep.id,:category = >'test',:status =>'ok') – 2009-05-19 17:14:03