如何在迁移时将数据添加到新创建的列中?

发布于 2024-11-09 15:10:42 字数 1156 浏览 0 评论 0原文

在已部署的应用程序中,在我的 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 表为空,因为数据将从< code>seeds.rb),因此 state_code 仍为 NULL

所以我的问题是(它们是如此相关,很抱歉没有将它们作为每个单独的问题提出):

  1. 重新创建数据库时如何填充 state_codes (在 states 之后)表中有数据)?
  2. 当部署的应用程序上的 rake db:migrate 时(seeds.rb 未在 rake db 上运行),如何获取 state_codes: migrate
  3. 我不应该首先使用seeds.rb(而是将数据放入迁移中)吗?

In an already-deployed application, in my seeds.rb, I have the following:

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

Now I wanted to add the two-letter code for each state.

So I made a migration like this:

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

Problem is:

In development environment, when I want to recreate the database from scratch, then after the migrations run, at that point the seeds.rb has not yet been run.

So, the UPDATE xxx in the AddStateCodeToStates migration has no data to work with (states table is empty because the data will be populated from the seeds.rb), thus the state_code remains NULL.

So my questions are (they are so related, so sorry for not asking them as each separate question):

  1. How do I populate the state_codes when recreating the database (after the states table has data in it)?
  2. How do I get the state_codes when rake db:migrate on the deployed app (seeds.rb does not run on rake db:migrate)
  3. Should I not have used seeds.rb in the first place (and instead put data into the migrations)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

年少掌心 2024-11-16 15:10:42

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

State.find_or_create_by_state(:state => 'state_name_here', ':state_code => 'code here')< /代码>

Like many things in Rails, you have many options, but.... general practice is to put necessary application data in seeds.rb. You should write seeds.rb in a way that it can be run multiple times without adding extra records, e.g.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文