0

I have a migration that uses the ActiveRecord concat method to add an object to another object's has_many relationship. Since creating the migration, I have added a new attribute to the parent model that includes a validation.

Unfortunately, the earlier migration is broken, as concat tries to save the parent object, and the validation cannot find the associated attribute (it doesn't exist yet). Am I doing the data migration incorrectly?

Here's the migration:

class RemoveTransportKeyFromInvites < ActiveRecord::Migration
  def up
    Invite.find_each do |invite|
      transport_key = Invite.where(id: invite.id).pluck(:transport_key).first
      guest_user = GuestUser.first_or_create!(transport_key: transport_key)
      guest_user.invites << invite
    end
    remove_column :invites, :transport_key
  end

  def down
    add_column :invites, :transport_key, :string
  end
end

And the model:

class Invite < ActiveRecord::Base
  # some code omitted
  validates_presence_of :inviter_email
  # rest of code omitted

Which causes this error:

undefined method `inviter_email' for #<InviteToMeal:0x007f8ece07c060>

Thanks, any help would be greatly appreciated!

1 Answers1

1

The prescribed method is to define a "stub" model in the migration so that the real model (with validations) doesn't get loaded. find_each and the other ActiveRecord calls will still work.

class RemoveTransportKeyFromInvites < ActiveRecord::Migration
  class Invite < ActiveRecord::Base; end

  def up
    # etc..

See this guide for more information.

Wally Altman
  • 3,535
  • 3
  • 25
  • 33