【发布时间】:2019-05-07 19:08:13
【问题描述】:
我正在进行重构,我为新传入数据编写了新模型,这些新模型将位于功能标志后面,同时为尚未拥有该功能的人的传入数据保持旧模型处于活动状态旗帜。新旧模型都与数据库中的同一张表进行交互。
即
class Poem < ApplicationRecord
belongs_to: :author
belongs_to: :anthology, optional: true
end
class Anthology < ApplicationRecord
belongs_to: :author
has_many: :poems
end
class Author < ApplicationRecord
has_many: :anthologies
has_many: :poems
end
class NewPoem < ApplicationRecord
self.table_name = 'poems'
belongs_to: :author, class_name: 'NewAuthor'
belongs_to: :anthology, class_name: 'NewAnthology', optional: true
end
class NewAnthology < ApplicationRecord
self.table_name = 'anthologies'
belongs_to: :author, class_name: 'NewAuthor'
has_many: :poems, class_name: 'NewPoem'
end
class NewAuthor < ApplicationRecord
self.table_name = 'authors'
has_many: :anthologies, class_name: 'NewAnthology'
has_many: :poems, class_name: 'NewPoem'
end
当我创建新书时,我想将新书分配给作者
anthology = Anthology.find(1)
@poem = NewPoem.new
@poem.author = anthology.author
这给了我一个错误
ActiveRecord::AssociationTypeMismatch (NewAuthor(#70008442274840) expected, got Author(#47031421032620)):
有没有办法解决这个问题?或者如果没有数据迁移,我将无法将模型与旧模型相关联?
【问题讨论】:
标签: ruby-on-rails activerecord refactoring associations