ruby-on-rails - 如何生成迁移以使引用多态

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

我有一个产品表并想要添加一列:

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 的稳定版本中实现,因此 Michelle 的答案目前是正确的。但该功能将在 Rails 4 中实现,并且已经在 Edge 版本中提供,如下(根据此 CHANGELOG ):

$ rails generate migration AddImageableToProducts imageable:references{polymorphic}

某些 shell 可能需要使用 \ 转义 {polymorphic}:

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

关于ruby-on-rails - 如何生成迁移以使引用多态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5534579/

相关文章:

ruby-on-rails - Rails 时间格式化测试失败是因为它休息了一小时?

ruby-on-rails - 如何使用户登录到子域并使 session 在另一个子域上可用?

ruby-on-rails - 在 Rails 中验证多态关联类型

sql-server - 在 SQL Server 中实现多态关联的最佳方法是什么?

mysql - 在没有 key 长度的 key 规范中使用的 Rails BLOB/TEXT 列

css - 为什么 Rails 会记住删除的 css?

ruby-on-rails - 为不同的用户配置文件设计具有多态关联的用户

ruby-on-rails - 我可以使用 ActiveRecord 迁移向表或列添加注释吗?

ruby-on-rails - 我可以将默认值传递给 rails 生成迁移吗?

ruby-on-rails - Rails Webpacker - 如何从 View [HTML 文件] 访问 webpack 条目文件中定义的对象