如何生成迁移以使引用具有多态性

时间:2011-04-04 04:31:34

标签: ruby-on-rails polymorphic-associations rails-migrations

我有一个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 个答案:

答案 0 :(得分:251)

你想要做的还没有在稳定版本的rails中实现,所以Brandon的答案现在是正确的。但是此功能将在rails 4中实现,并且已在边缘版本中提供,如下所示(根据此CHANGELOG):

$ rails generate migration AddImageableToProducts imageable:references{polymorphic}

答案 1 :(得分:102)

据我所知,没有用于多态关联的内置生成器。生成空白迁移,然后根据需要手动修改。

<强>更新: 您需要指定要更改的表。根据{{​​3}}:

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

答案 2 :(得分:31)

您还可以执行以下操作:

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

答案 3 :(得分:13)

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

相关问题