我有一个Rails项目,我需要一些默认值添加到数据库表中加载默认值的数据库。我想知道做这些的(使用Rails 2.3.3 IM不具有seed.rb文件:()的最佳方式最佳实践,以在轨
1 - 创建一个SQL脚本
2 - 创建迁移
3 - 创建一个rake任务
4 - 其他(请注明)提前
感谢
欢呼
sameera
我有一个Rails项目,我需要一些默认值添加到数据库表中加载默认值的数据库。我想知道做这些的(使用Rails 2.3.3 IM不具有seed.rb文件:()的最佳方式最佳实践,以在轨
1 - 创建一个SQL脚本
2 - 创建迁移
3 - 创建一个rake任务
4 - 其他(请注明)提前
感谢
欢呼
sameera
看看seed-fu。
在Rails的电流稳定版本(2.3.8)有耙任务分贝:种子,其以db/seeds.rb文件执行代码。在该文件中,可以通过直接执行Rails代码加载你数据(News.create:标题=>“测试” ...),或使用您喜欢的任何其它方法。
我宁愿加载从夹具数据,原因夹具可在测试以后被使用。我使用rspec,所以我的灯具存储在spec/fixtures /目录中。
您可以使用下面的代码从现有的SQL表使灯具:
def make_fixtures(tablenames, limit = nil)
sql = "SELECT * FROM %s"
sql += " LIMIT #{limit}" unless limit.nil?
dump_tables = tablenames.to_a
dump_tables.each do |table_name|
i = "000"
file_name = "#{RAILS_ROOT}/spec/fixtures/#{table_name}.yml"
puts "Fixture save for table #{table_name} to #{file_name}"
File.open(file_name, 'w') do |file|
data = ActiveRecord::Base.connection.select_all(sql % table_name)
file.write(data.inject({}) do |hash, record|
hash["#{table_name}_#{i.succ!}"] = record
hash
end.to_yaml)
end
end
end
以dB/seeds.rb你可以从灯具加载:
require 'active_record/fixtures'
[ "classifiers", "roles", "countries", "states", "metro_areas" ].each do |seed|
puts "Seeding #{seed}..."
Fixtures.create_fixtures(File.join(Rails.root, "spec", "fixtures"), seed)
end
喜约翰 感谢,将签 欢呼 sameera – sameera207 2010-08-10 09:47:21