How to add data to a newly created column in migration?
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 (sta开发者_开发知识库tes
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)?
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')
精彩评论