Pab*_*dez 20 database migration ruby-on-rails
我想知道哪些是在Rails迁移中向数据库表添加记录的首选方法.我读过Ola Bini的书(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
Run Code Online (Sandbox Code Playgroud)
这很干净但是由于某些原因,它不适用于持续版本的导轨......
问题是,如何使用默认数据(如用户或其他东西)填充数据库?
谢谢!
And*_*son 38
用于迁移的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
Run Code Online (Sandbox Code Playgroud)
在Rails 2.3.0上测试过,但这也适用于许多早期版本.
Kel*_*tia 10
你可以使用灯具.这意味着在某个地方有一个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
Run Code Online (Sandbox Code Playgroud)
db/migrate/init_data/profiles.yaml
admin:
name: Admin
value: 1
normal:
name: Normal user
value: 2
Run Code Online (Sandbox Code Playgroud)
您也可以在seeds.rb文件中定义,例如:
Grid.create :ref_code => 'one' , :name => 'Grade Única'
Run Code Online (Sandbox Code Playgroud)
并在运行后:
rake db:seed
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23497 次 |
| 最近记录: |