Re: migrations ignoring record changes

Rob Biedenharn
Mon, 07 Jan 2008 19:14:49 -0000

In general, you have to tell ActiveRecord that it needs to rethink the
columns that the database has:

	User.reset_column_information

But in this case, there''s not really a need to get the model involved.

	User.update_all([''first_name = ?, last_name = ?'',
"First", "Last"])

will do the same think (and a lot faster, too!)

-Rob

On Jan 7, 2008, at 1:37 PM, Josh wrote:
> Almost immediately after posting this, I tried splitting this into two
> separate migrations. One to add/remove the columns and the one after
> that to update all of the records in the database. Running rake
> db:migrate and updating everything at once didn''t work, but
running
> the migration all the way up to the version that adds the columns, and
> then re-running rake db:migrate a second time worked. So I guess the
> model is just not being reloaded once the new columns are added.
>
> Is it possible that this is a bug, or is this the way it was meant to
> work?
>
> On Jan 7, 12:30 pm, Josh
<jjkie...-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:
>> I had a users table and went back to add columns for first name and
>> last name. Just so it would not cause errors, I was trying to loop
>> through the existing users in the database and set the first name
>> column to "First" and the last name column to
"Last"
>>
>> Before updating to rails 2, i was able to do something like this:
>>
>> class AddFirstNameAndLastNameToUsers < ActiveRecord::Migration
>>  def self.up
>>    add_column :users, :first_name, :string
>>    add_column :users, :last_name, :string

      User.reset_column_information

>>    User.find(:all).each do |user|
>>      user.first_name = ''First''
>>      user.last_name = ''Last''
>>      user.save
>>    end
>>  end
>>
>>  def self.down
>>    remove_column :users, :first_name
>>    remove_column :users, :last_name
>>  end
>> end
>>
>> For some reason, the columns are created, but the names are never
>> changed. When looking at the database, everything is still NULL. When
>> calling save on the user object, I see MYSQL updates being made, but
>> without the columns that were just added.
>>
>> I can''t figure out why this won''t work and would
greatly appreciate
>> any insight.
>>
>> Thanks.

Rob Biedenharn		http://agileconsultingllc.com
Rob-xa9cJyRlE0mWcWVYNo9pwxS2lgjeYSpx@public.gmane.org