在迁移上添加行 [英] Add Rows on Migrations

查看:148
本文介绍了在迁移上添加行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在Rails迁移中将记录添加到数据库表的首选方式。我读了Ola Bini的书(Jruby on Rails),他做了这样的事情:

  class CreateProductCategories< ActiveRecord :: Migration 

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

def self.up

#CREATE THE TABLES ...

load_data
end
def self.load_data
#使用AR对象创建默认数据
ProductType.create(:name =>type)
end
end



这是很好,干净,但由于某些原因,不工作的最后版本的rails ...



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



谢谢!

解决方案

你可以使用fixtures。



这是我在我的应用程序中为此所做的一个更改集:



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(目录,profiles)
end

def self.down
Profile.delete_all
end
end

db / migrate / init_data / profiles.yaml

 管理员:
名称:Admin
值:1
正常:
名称:正常用户$ b b value:2


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

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)?

Thanks!

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆