【问题标题】:How to add data to a newly created column in migration?如何在迁移中向新创建的列添加数据?
【发布时间】:2011-09-01 04:25:32
【问题描述】:

在一个已经部署的应用程序中,在我的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. 当rake db:migrate 在已部署的应用程序上时,我如何获得state_codes(seeds.rb 不在rake db:migrate 上运行)
  3. 我不应该首先使用seeds.rb(而是将数据放入迁移中)吗?

【问题讨论】:

    标签: ruby-on-rails-3 seed


    【解决方案1】:

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

    State.find_or_create_by_state(:state =&gt; 'state_name_here', ':state_code =&gt; 'code here')

    【讨论】:

      猜你喜欢
      • 2015-09-02
      • 2014-12-25
      • 2014-12-26
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      相关资源
      最近更新 更多