關於你的問題而言,這裏就是我想要做的:
您的Bar
模型中的所有數據將根據Bar
模型進行存儲。這意味着如果您更改模型中的foo_id
屬性,則只需填充需要添加的bar_type
屬性(因爲它們都可以引用相同的模型)
要實現的方法這是如下:
- 創建遷移
foo_id
>fooable_id
- 通過所有現有的記錄插入
fooable_type
列
- 在軌控制檯,環0,第一填充
fooable_type
列
第一件事:
$軌摹遷移ChangeFooID
#db/migrate/latest.rb
class Latest
def change
rename_column :bars, :foo_id, :fooable_id
add_column :bars, :fooable_type, :string, after: :id
end
end
這將創建不同的列給你的。然後你只需要能夠循環通過記錄&改變type
柱:
軌道ç
Bar.find_each do |bar|
bar.update(barable_type: "Foo")
end
這將允許您更改列的類型,給你將所有當前記錄與相應記錄相關聯的能力。
多態性
您就可以use the Rails docs as a reference爲如何將模型相關聯:
#app/models/foo.rb
class Foo < ActiveRecord::Base
has_many :bars, as: :barable
end
#app/models/bar.rb
class Bar < ActiveRecord::Base
belongs_to :foo, polymorphic: true
end
哦,哇,你還在使用Rails 2?這是真的還是錯字? – 2014-08-29 08:26:42