how to generate migration to make references polymorphic

Ruby on-RailsPolymorphic AssociationsRails Migrations

Ruby on-Rails Problem Overview


I have a Products table and want to add a column:

t.references :imageable, :polymorphic => true

I was trying to generate migration for this by doing:

$ rails generate migration AddImageableToProducts imageable:references:polymorphic

but I am obviously doing it wrong. Can anybody make any suggestion? Thanks

When I try to manually put it in after generating the migration, I did it like this:

class AddImageableToProducts < ActiveRecord::Migration
  def self.up
    add_column :products, :imageable, :references, :polymorphic => true
  end

  def self.down
    remove_column :products, :imageable
  end
end

and it still hasn't worked

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

What you are trying to do is not yet implemented in the stable version of rails so Michelle's answer is the right one for now. But this feature will be implemented in rails 4 and is already available in the edge version as follows (according to this CHANGELOG):

$ rails generate migration AddImageableToProducts imageable:references{polymorphic}

Some shells may need {polymorphic} escaped with a \:

$ rails generate migration AddImageableToProducts imageable:references\{polymorphic\}

Solution 2 - Ruby on-Rails

Before Rails 4 there was no built-in generator for polymorphic associations. If you are using an early version of Rails generate a blank migration and then modify it by hand according to your needs.

Update: You'll need to specify which table you're changing. According to this SO answer:

class AddImageableToProducts < ActiveRecord::Migration
  def up
    change_table :products do |t|
      t.references :imageable, polymorphic: true
    end
  end

  def down
    change_table :products do |t|
      t.remove_references :imageable, polymorphic: true
    end
  end
end

Rails 4 added a generator for polymorphic associations (see simon-olivier answer)

Solution 3 - Ruby on-Rails

You could also do the following:

class AddImageableToProducts < ActiveRecord::Migration
  def change
    add_reference :products, :imageable, polymorphic: true, index: true
  end
end

Solution 4 - Ruby on-Rails

You can try rails generate migration AddImageableToProducts imageable:references{polymorphic}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrailslearnerView Question on Stackoverflow
Solution 1 - Ruby on-Railssimon-olivierView Answer on Stackoverflow
Solution 2 - Ruby on-RailsMichelle TilleyView Answer on Stackoverflow
Solution 3 - Ruby on-RailsfreddyrangelView Answer on Stackoverflow
Solution 4 - Ruby on-RailshutusiView Answer on Stackoverflow