2011-05-24 62 views
1

在已部署的应用程序,在我seeds.rb,我有以下几点:如何在迁移中将数据添加到新创建的列中?

State.create!(:state => "Alabama") 
State.create!(:state => "Delaware") 
... 

现在我想补充的两个字母的代码,每个状态。

所以我做了这样的迁移:

class AddStateCodeToStates < ActiveRecord::Migration 
    def self.up 
    add_column :states, :state_code, :string 

    update(<<-SQL 
    UPDATE states SET state_code='WA' where state = 'Washington' 
    SQL 
    ) 
    ...lots of these SQL statement... 
    end 

    def self.down 
    end 
end 

问题是:

在开发环境中,当我想从头开始重新创建数据库,那么迁移运行后,在那点seeds.rb尚未运行。

所以,在AddStateCodeToStates迁移UPDATE xxx没有数据一起工作(states表是空的,因为数据将从seeds.rb填充),因此state_code保持NULL

所以我的问题是(他们是如此相关,所以抱歉,没有要求他们为每个单独的问题):

  1. 如何填充state_codes重新创建数据库(states表后,当有数据它)?
  2. 我如何在部署应用程序的state_codesrake db:migrateseeds.rb不上rake db:migrate运行)
  3. 我应该不会在第一时间使用seeds.rb(而是把数据放到迁移)?

回答

3

像Rails中的许多事情一样,您有很多选择,但是......一般的做法是将必要的应用程序数据放入seeds.rb。您应该以可以多次运行而不添加额外记录的方式编写seeds.rb,例如

State.find_or_create_by_state(:state => 'state_name_here', ':state_code => 'code here')

相关问题