Search code examples
ruby-on-railsconsoledata-migration

rails migration script VS console


so i am trying to migrate some data in a migration script, but the data does not seem to be saving. however, if i copy the code and run it directly in the console, it does save. can anyone help me figure out why?

this is the code from my migration script. i am moving my avatar data from its own table into my profiles table.

  def self.up
    add_column :users,    :featured,            :boolean, :default => false
    add_column :profiles, :avatar_file_name,    :string
    add_column :profiles, :avatar_content_type, :string
    add_column :profiles, :avatar_file_size,    :integer
    add_column :profiles, :avatar_updated_at,   :datetime

    Avatar.all.each do |a|
      user = User.find(a.user_id)
      user.profile.avatar_file_name = a.avatar_file_name
      user.profile.avatar_content_type = a.avatar_content_type
      user.profile.avatar_file_size = a.avatar_file_size
      user.profile.avatar_updated_at = a.updated_at
      if a.featured == true
        user.featured = true
      end
      user.save
    end

    # drop_table :avatars
  end

Solution

  • I think it's because you're changing the columns and trying to use them in the same migration, but the model doesn't know about the fields.

    Try adding these lines above Avatar.all.each...

    User.reset_column_information
    Profile.reset_column_information
    

    More about this http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-reset_column_information