Ruby-on-rails 如何生成迁移以使引用多态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5534579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to generate migration to make references polymorphic
提问by railslearner
I have a Products table and want to add a column:
我有一个 Products 表,想添加一列:
t.references :imageable, :polymorphic => true
I was trying to generate migration for this by doing:
我试图通过执行以下操作来生成迁移:
$ rails generate migration AddImageableToProducts imageable:references:polymorphic
but I am obviously doing it wrong. Can anybody make any suggestion? Thanks
但我显然做错了。有人可以提出任何建议吗?谢谢
When I try to manually put it in after generating the migration, I did it like this:
当我尝试在生成迁移后手动放入它时,我是这样做的:
class AddImageableToProducts < ActiveRecord::Migration
def self.up
add_column :products, :imageable, :references, :polymorphic => true
end
def self.down
remove_column :products, :imageable
end
end
and it still hasn't worked
它仍然没有奏效
采纳答案by Michelle Tilley
As far as I know, there's no built-in generator for polymorphic associations. Generate a blank migration and then modify it by hand according to your needs.
据我所知,没有用于多态关联的内置生成器。生成一个空白迁移,然后根据您的需要手动修改它。
Update: You'll need to specify which table you're changing. According to this SO answer:
更新:您需要指定要更改的表。根据这个 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
回答by simon-olivier
What you are trying to do is not yet implemented in the stable version of rails so Michelle's answer is the right one for now. But this feature will be implemented in rails 4 and is already available in the edge version as follows (according to this CHANGELOG):
您正在尝试做的尚未在稳定版本的 rails 中实现,因此 Michelle 的答案目前是正确的。但是此功能将在 rails 4 中实现,并且已经在边缘版本中可用,如下所示(根据此CHANGELOG):
$ rails generate migration AddImageableToProducts imageable:references{polymorphic}
回答by freddyrangel
You could also do the following:
您还可以执行以下操作:
class AddImageableToProducts < ActiveRecord::Migration
def change
add_reference :products, :imageable, polymorphic: true, index: true
end
end
回答by hutusi
You can try rails generate migration AddImageableToProducts imageable:references{polymorphic}
你可以试试 rails generate migration AddImageableToProducts imageable:references{polymorphic}

