在迁移中添加行 [英] Add Rows on Migrations
问题描述
我想知道在 Rails 迁移中向数据库表添加记录的首选方式是哪种.我在 Ola Bini 的书(Jruby on Rails)上读到他做了这样的事情:
I'd like to know which is the preferred way to add records to a database table in a Rails Migration. I've read on Ola Bini's book (Jruby on Rails) that he does something like this:
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
这很好而且很干净,但由于某种原因,它不适用于最新版本的 rails...
This is nice and clean but for some reason, doesn't work on the lasts versions of rails...
问题是,如何使用默认数据(如用户或其他内容)填充数据库?
The question is, how do you populate the database with default data (like users or something)?
谢谢!
推荐答案
您可以为此使用固定装置.这意味着在某个地方有一个 yaml 文件,其中包含您要插入的数据.
You could use fixtures for that. It means having a yaml file somewhere with the data you want to insert.
这是我在我的一个应用中为此提交的变更集:
Here is a changeset I committed for this in one of my app:
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
这篇关于在迁移中添加行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!