2009-01-06 98 views
17

我想知道哪些是在Rails迁移中将记录添加到数据库表的首选方式。我读过奥拉·比尼的书(的JRuby on Rails的),他做这样的事情:添加行迁移

class CreateProductCategories < ActiveRecord::Migration 

    #defines the AR class 
    class ProductType < ActiveRecord::Base; end 

    def self.up 

    #CREATE THE TABLES... 

    load_data 
    end 
    def self.load_data 
    #Use AR object to create default data 
    ProductType.create(:name => "type") 
    end 
end 

这是非常干净的,但出于某种原因,不能正常工作的持续轨的版本...

问题是,你如何填充数据库与默认数据(如用户或东西)?

谢谢!

+0

这几乎是我做什么,请包括您所收到的错误。 – 2009-01-06 03:24:55

+0

完整的代码是这样的:http://pastie.org/pastes/251539 而错误是'CreateProductCategories不缺少常量ProductType' – 2009-01-06 04:14:31

回答

9

你可以使用灯具。这意味着在你想插入的数据的某个地方有一个yaml文件。

这里是一个变更我在我的应用程序的一个致力于此:

db/migrate/004_load_profiles.rb

require 'active_record/fixtures' 

class LoadProfiles < ActiveRecord::Migration 
    def self.up 
    down() 

    directory = File.join(File.dirname(__FILE__), "init_data") 
    Fixtures.create_fixtures(directory, "profiles") 
    end 

    def self.down 
    Profile.delete_all 
    end 
end 

db/migrate/init_data/profiles.yaml

admin: 
name: Admin 
    value: 1 
normal: 
name: Normal user 
    value: 2 
3

您的迁移可以访问您的所有模型,因此您不应该在迁移内部创建类。

我正在使用最新的导轨,我可以确认您发布的例子绝对是OUGHT的工作。

但是,迁徙是一种特殊的野兽。只要你清楚,我没有看到ActiveRecord::Base.connection.execute("INSERT INTO product_types (name) VALUES ('type1'), ('type2')")有什么问题。

这样做的好处是,您可以通过使用某种GUI或Web前端轻松生成它以填充您的起始数据,然后执行mysqldump -uroot database_name.product_types

无论对于那些将要执行迁移和维护产品的人来说,事情都是最简单的。

35

的迁移Rails的API文档显示了一个更简单的方法来实现这个。

http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

class CreateProductCategories < ActiveRecord::Migration 
    def self.up 
    create_table "product_categories" do |t| 
     t.string name 
     # etc. 
    end 

    # Now populate the category list with default data 

    ProductCategory.create :name => 'Books', ... 
    ProductCategory.create :name => 'Games', ... # Etc. 

    # The "down" method takes care of the data because it 
    # drops the whole table. 

    end 

    def self.down 
    drop_table "product_categories" 
    end 
end 

测试on Rails的2.3.0,但这应该对很多早期版本的工作了。

7

你也可以定义你的seeds.rb文件,例如:

Grid.create :ref_code => 'one' , :name => 'Grade Única' 

和运行后:

rake db:seed 
0

你真的应该不使用

ProductType.create 

您迁移。

我已经做了类似的事情,但从长远来看,他们不能保证工作。

运行迁移时,您使用的模型类是运行迁移时的模型类,而不是创建迁移时的模型类。你必须确保你永远不会改变你的模型,从而阻止你从运行迁移。

你好得多运行SQL例如:

[{name: 'Type', ..}, .. ].each do |type| 
    execute("INSERT INTO product_types (name) VALUES ('#{type[:name]} ..) 
end