【问题标题】:how to generate migration to make references polymorphic如何生成迁移以使引用多态
【发布时间】:2011-07-28 22:06:01
【问题描述】:

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

还是不行

【问题讨论】:

  • 不是一个答案,但为了避免混淆,您确定想要这个关于产品的专栏吗? rails 指南甚至有一个 Products 示例,该列在图片上guides.rubyonrails.org/…
  • 这很方便::references{polymorphic}。例如,rails generate migration AddImageableToProducts imageable:references:{polymorphic}Source

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


【解决方案1】:

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

$ rails generate migration AddImageableToProducts imageable:references{polymorphic}

【讨论】:

  • 在 4.2 上试过这个,我不确定这是一个 bug、zsh 还是其他东西,但是命令行被解释为一系列引用(作为类型),每个字母的多态,例如:t.referencesp :imagable、treferenceso :imagable 等。
  • @OzBarry,在 zsh 中你需要转义大括号: $ rails generate migration AddImageableToProducts imageable:references\{polymorphic\}
  • 对于任何好奇的人,这会生成一个带有更改方法的迁移,其中包含:add_reference :products, :imageable, polymorphic: true, index: true
  • 如果有人试图在脚手架中使用相同的,这也适用于脚手架。谢谢!赖克斯
  • {polymorphic} 需要用鱼壳转义,例如\{polymorphic\}
【解决方案2】:

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

更新: 您需要指定要更改的表。根据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 为多态关联添加了一个生成器(请参阅 simon-olivier 答案)

【讨论】:

  • 非常感谢布兰登。我能够运行迁移。不过我想知道,在您设置 :polymorphic => true 并打开 schema.rb 之后,您是否也应该在架构中看到它?
  • 运行迁移后,schema.rb 应该会更新,但它不会说任何关于 polymorphic 的信息。相反,您应该看到 Rails 使用的实际字段(Rails Guides 有更多信息)。
  • 如何将索引添加到references 列?我需要索引吗?
  • @mrudult 如果我没记错的话,如果你需要的话,你需要自己添加它们。您可以根据需要在迁移文件中正常添加索引到imageable_type 和/或imageable_id
  • 是的。将索引添加到 imageable_idimageable_type 有效。感谢您的帮助。
【解决方案3】:

您还可以执行以下操作:

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

【讨论】:

    【解决方案4】:

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

    【讨论】:

    • {} 至少需要用鱼壳转义,例如\{polymorphic\}
    • 这里是相关文档的链接:edgeguides.rubyonrails.org/…
    • 谢谢乔瓦尼,这非常有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 2015-03-29
    • 2018-05-02
    • 2015-12-07
    相关资源
    最近更新 更多