Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to add data to a newly created column in migration?
    text
    copied!<p>In an already-deployed application, in my <code>seeds.rb</code>, I have the following:</p> <pre><code>State.create!(:state =&gt; "Alabama") State.create!(:state =&gt; "Delaware") ... </code></pre> <p>Now I wanted to add the two-letter code for each state.</p> <p>So I made a migration like this:</p> <pre><code>class AddStateCodeToStates &lt; ActiveRecord::Migration def self.up add_column :states, :state_code, :string update(&lt;&lt;-SQL UPDATE states SET state_code='WA' where state = 'Washington' SQL ) ...lots of these SQL statement... end def self.down end end </code></pre> <p><strong>Problem is:</strong></p> <p>In development environment, when I want to recreate the database from scratch, then after the migrations run, at that point the <code>seeds.rb</code> has not yet been run.</p> <p>So, the <code>UPDATE xxx</code> in the <code>AddStateCodeToStates</code> migration has no data to work with (<code>states</code> table is empty because the data will be populated from the <code>seeds.rb</code>), thus the <code>state_code</code> remains <code>NULL</code>.</p> <p>So my questions are (they are so related, so sorry for not asking them as each separate question):</p> <ol> <li>How do I populate the <code>state_codes</code> when recreating the database (after the <code>states</code> table has data in it)?</li> <li>How do I get the <code>state_codes</code> when <code>rake db:migrate</code> on the deployed app (<code>seeds.rb</code> does not run on <code>rake db:migrate</code>)</li> <li>Should I not have used <code>seeds.rb</code> in the first place (and instead put data into the migrations)?</li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload