141

我有一个 Products 表并想添加一列:

t.references :imageable, :polymorphic => true

我试图通过执行以下操作为此生成迁移:

$ rails generate migration AddImageableToProducts imageable:references:polymorphic

但我显然做错了。有人可以提出任何建议吗?谢谢

当我在生成迁移后尝试手动放入时,我是这样做的:

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

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

它仍然没有工作

4

4 回答 4

303

您正在尝试做的事情尚未在稳定版本的 rails 中实现,因此 Michelle 的答案目前是正确的。但是这个特性将在 rails 4 中实现,并且已经在边缘版本中可用,如下所示(根据这个CHANGELOG):

$ rails generate migration AddImageableToProducts imageable:references{polymorphic}
于 2013-03-04T15:02:12.737 回答
120

在 Rails 4 之前,没有内置的多态关联生成器。如果您使用的是早期版本的 Rails,请生成一个空白迁移,然后根据您的需要手动修改它。

更新:您需要指定要更改的表。根据这个答案

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 添加了一个用于多态关联的生成器(参见 simon-olivier 答案)

于 2011-04-04T04:38:50.377 回答
47

您还可以执行以下操作:

class AddImageableToProducts < ActiveRecord::Migration
  def change
    add_reference :products, :imageable, polymorphic: true, index: true
  end
end
于 2014-11-24T21:38:27.913 回答
18

你可以试试rails generate migration AddImageableToProducts imageable:references{polymorphic}

于 2017-09-13T07:17:40.067 回答