如果您具有多态belongs_to关联,那么引用将添加所需的两列:
create_table :products do |t|
t.references :attachment, :polymorphic => {:default => 'Photo'}
end
将添加一个attachment_id
列和字符串attachment_type
默认值为“照片”的列。
这到底是什么意思?
这是有关参考方法的文档:http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#M001938 http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#M001938
引用方法的代码如下:
497: def references(*args)
498: options = args.extract_options!
499: polymorphic = options.delete(:polymorphic)
500: args.each do |col|
501: column("#{col}_id", :integer, options)
502: column("#{col}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) unless polymorphic.nil?
503: end
504: end
如你看到的。它将 [column]_id 和 [column type 列添加到表中。
这就像说一样:
create_table :products do |t|
t.integer :attachment_id
t.string :attachment_type, :default => 'Photo'
end
多态关联用于将一种对象连接到多种其他对象。
一个很好的例子可能是支持标签的应用程序,其中标签可以连接到Products
and Categories
.
在您的示例中,产品看起来可以附加到多种类型的对象,其中默认类型的对象是照片。 (attachment_type
将是“照片”,并且attachment_id
将是“照片”表中一行的 ID)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)