0

I am trying to fun a migration to shift some data around. In the previous migration I run the following:

add_column :portfolios, :owner_id, :integer

Then in the following migration is as follows: class MoveUserIdToPortfolio < ActiveRecord::Migration

  class Stake < ActiveRecord::Base
  end

  class UserStakeInPortfolio < Stake
    belongs_to :portfolio, foreign_key: :possession_id

    def self.sti_name
      'UserStakeInPortfolio'
    end
  end

  class User < ActiveRecord::Base
    has_many :user_stake_in_portfolios, foreign_key: :owner_id
    has_many :portfolios, through: :user_stake_in_portfolios
    has_many :personal_portfolios, through: :user_stake_in_portfolios, :class_name => 'PersonalPortfolio', :source => :portfolio, :conditions => { :type => 'PersonalPortfolio' }

    def personal_portfolio
      self.personal_portfolios.first
    end
  end

  class Portfolio < ActiveRecord::Base
  end

  class PersonalPortfolio < Portfolio

    def self.sti_name
      'PersonalPortfolio'
    end
  end

  def up

    puts "DEBUG: #{Portfolio.inspect}"

    Portfolio.connection.schema_cache.clear!
    Portfolio.reset_column_information
    PersonalPortfolio.connection.schema_cache.clear!
    PersonalPortfolio.reset_column_information
    User.connection.schema_cache.clear!
    User.reset_column_information

    puts "DEBUG2: #{Portfolio.inspect}"

    User.all.each do |user|
      pp = user.personal_portfolio
      puts "DEBUG3: #{pp.inspect}"
      pp.owner_id = user.id
      pp.save
      puts "DEBUG4: #{pp.inspect}"
    end

  end

  def down

  end
end

The strange thing here is that the pp.owner_id is never set. And the output (that follows) never shows it attempting to update the owner_id, although it doesn't error out.

(0.1ms)  BEGIN
(0.3ms)  UPDATE `portfolios` SET `updated_at` = '2013-09-11 22:16:06' WHERE `portfolios`.`type` IN ('PersonalPortfolio') AND `portfolios`.`id` = 4
(0.4ms)  COMMIT

The DEBUG statement shows a Portfolio without an owner_id attribute. But the DEBUG2 outputs it with one. But the the two pp.inspect outputs both do not show an instance with owner_id.

Happy to provide more information if it's helpful!

Ryan
  • 641
  • 5
  • 17
  • 1
    Can you change save to save!, so we can see the exception that is getting raised (if any). – steakchaser Sep 11 '13 at 22:48
  • Also, I almost always prefer to use update_all in a migration so that the migration can remain as independent from the model code as possible. Using active record in a migration can cause you to run into scenarios where you can't run the migration without having the correct version of the model code in place at the same time. – steakchaser Sep 11 '13 at 22:50
  • It doesn't product any error when using `save!`. Same thing happens. Also, not sure how to use update_all in this situation as the value is different for each portfolio. – Ryan Sep 23 '13 at 18:36

0 Answers0