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:


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!