在Rails迁移中加载数据

时间:2009-05-19 16:57:43

标签: ruby-on-rails migration

我创建了一系列迁移,从Posts表的定义开始。

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

另一个用于Users表,在创建表后我为默认用户加载了一些数据。

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 => 'bo@peep.com',
      :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而不是“BlogPost.create”?

1 个答案:

答案 0 :(得分:5)

将rename_table和更改/重命名列迁移分离到另一个迁移文件中。

我不认为重命名是在整个块经过之后才提交的......因此blog_posts尚不存在。