如何在迁移时将数据添加到新创建的列中?
在已部署的应用程序中,在我的 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
。
所以我的问题是(它们是如此相关,很抱歉没有将它们作为每个单独的问题提出):
- 重新创建数据库时如何填充
state_codes
(在states
之后)表中有数据)? - 当部署的应用程序上的
rake db:migrate
时(seeds.rb
未在rake db 上运行),如何获取
)state_codes
: migrate - 我不应该首先使用
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):
- How do I populate the
state_codes
when recreating the database (after thestates
table has data in it)? - How do I get the
state_codes
whenrake db:migrate
on the deployed app (seeds.rb
does not run onrake db:migrate
) - Should I not have used
seeds.rb
in the first place (and instead put data into the migrations)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
与 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')