Search code examples
ruby-on-railsactiverecordmigrationruby-on-rails-2

How to change a reference column to be polymorphic?


My model (Bar) already has a reference column, let's call it foo_id and now I need to change foo_id to fooable_id and make it polymorphic.

I figure I have two options:

  • Create new reference column fooable which is polymorphic and migrate the ID's from foo_id (What would be the best way to migrate these? Could I just do Bar.each { |b| b.fooable_id = b.foo_id }?
  • Rename foo_id to fooable_id and add polymorphic to fooable_id. How to add polymorpic to an existing column?

Solution

  • 1. Change the name of foo_id to fooable_id by renaming it in a migration like:

    rename_column :bars, :foo_id, :fooable_id
    

    2. and add polymorphism to it by adding the required foo_type column in a migration:

    add_column :bars, :fooable_type, :string
    

    3. and in your model:

    class Bar < ActiveRecord::Base
      belongs_to :fooable, 
        polymorphic: true
    end
    

    4. Finally seed the type of you already associated type like:

    Bar.update_all(fooable_type: 'Foo')
    

    Read Define polymorphic ActiveRecord model association!