Module: BelongsToMany::Migrations

Included in:
BelongsToMany
Defined in:
lib/vex/active_record/belongs_to_many.rb

Instance Method Summary collapse

Instance Method Details

#migrate(klass, up_or_down, *assocs) ⇒ Object

e.g.

migrate_belongs_to_many(:old_belongings => :belongings)

105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/vex/active_record/belongs_to_many.rb', line 105

def migrate(klass, up_or_down, *assocs)
  klass.reset_column_information

  case up_or_down
  when :down  then assocs.map! { |assoc| [ "#{assoc}", "#{assoc}_superseded" ] }
  when :up    then assocs.map! { |assoc| [ "#{assoc}_superseded", "#{assoc}" ] }
  end
  
  klass.all.with_progress.each do |model|
    assocs.each do |from, to|
      model.send "#{to}=", model.send(from)
    end

    # Try to save. Warn, if that fails.
    unless model.save
      STDERR.puts "#{model.class}##{model.id}: #{errors.full_messages.join(", ")}"
      model.save_without_validation
    end

    # verify migration...

    new_model = klass.find(model.id)

    assocs.each do |from, to|
      next if new_model.send(to) == model.send(from)
      STDERR.puts "#{model.class}##{model.id}: Mismatch on ##{from.inspect} -> #{to.inspect}" 
    end

    self
  end
end