【译】隔离种子数据(Isolating Seed Data)

Sunday, July 25, 2010

原文:http://rails-bestpractices.com/posts/20-isolating-seed-data

在Rails 2.3.4提供了db:seed这样一个rake任务,用来在创建新应用时候插入种子数据

丑陋的...

class CreateRoles < ActiveRecord::Migration
  def self.up
    create_table "roles", :force => true do |t|
      t.string :name
    end

["admin", "author", "editor", "account"].each do |name|
      Role.create!(:name => name)
    end
  end

def self.down
    drop_table "roles"
  end
end

以前我们总是在迁移中插入数据, 这不是个好方法, 这样把迁移搞得混乱,更好的方法是把所有的数据初始化移到seed.rb来

重构...

# db/seeds.rb (Rails 2.3.4)
["admin", "author", "editor", "account"].each do |name|
  Role.create!(:name => name)
end

rake db:seed

# lib/tasks/dev.rake (before Rails 2.3.4)
namespace :dev do

desc "Setup seed data"
  task :setup => :environment do
    ["admin", "author", "editor", "account"].each do |name|
      Role.create!(:name => name)
    end
  end
end

rake dev:setup

就这么简单, 所有的种子数据都放到了一个文件中,这样更易于维护。

This entry was tagged Rails and Best-Practices

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top