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

rai*_*ner 116 ruby-on-rails polymorphic-associations rails-migrations

我有一个Products表,想要添加一列:

t.references :imageable, :polymorphic => true
Run Code Online (Sandbox Code Playgroud)

我试图通过以下方式为此生成迁移:

$ rails generate migration AddImageableToProducts imageable:references:polymorphic
Run Code Online (Sandbox Code Playgroud)

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

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

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

  def self.down
    remove_column :products, :imageable
  end
end
Run Code Online (Sandbox Code Playgroud)

它仍然没有奏效

小智 255

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

$ rails generate migration AddImageableToProducts imageable:references{polymorphic}
Run Code Online (Sandbox Code Playgroud)

  • @OzBarry,在zsh中你需要逃避大括号:$ rails生成迁移AddImageableToProducts imageable:references\{polymorphic \} (10认同)
  • 对于任何好奇的人来说,这会生成一个带有change方法的迁移,其中包含:`add_reference:products,:imageable,polymorphic:true,index:true` (4认同)
  • 在 4.2 上试过这个,我不确定这是一个错误、zsh 还是其他什么,但是命令行被解释为一系列引用(作为类型),每个字母都是多态的,比如: t.referencesp :imagable , treferenceso :imagable 等。 (2认同)
  • 如果有人试图在脚手架中使用相同的东西,这也适用于脚手架。谢谢!瑞克斯 (2认同)
  • `{polymorphic}`需要使用fish shell进行转义,例如`\ {polymorphic \}` (2认同)

Mic*_*ley 106

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

更新:您需要指定要更改的表.根据这个SO回答:

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
Run Code Online (Sandbox Code Playgroud)

  • 如何在“引用”列中添加索引?我需要索引吗? (2认同)
  • 对.添加索引到`imageable_id`和`imageable_type`工作.谢谢你的帮助. (2认同)

fre*_*gel 33

您还可以执行以下操作:

class AddImageableToProducts < ActiveRecord::Migration
  def change
    add_reference :products, :imageable, polymorphic: true, index: true
  end
end
Run Code Online (Sandbox Code Playgroud)


hut*_*usi 16

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

  • `{`和`}`需要至少使用鱼壳进行转义,例如`\ {polymorphic \}` (3认同)