我正在使用以下模式创建我的应用的第二个版本:
class List < ActiveRecord::Base
has_many :listable_items
has_many :lists, through: :listable_items, source: :listable, source_type: 'List'
end
class ListableItem < ActiveRecord::Base
belongs_to :list
belongs_to :listable, polymorphic: true
end
module V2
class List < List
has_many :listable_items
has_many :lists, through: :listable_items, source: :listable, source_type: 'V2::List'
self.inheritance_column = :_non_existing_column
end
end
Module V2
class ListableItem < ListableItem
belongs_to :list, class_name: "V2::List"
belongs_to :listable, polymorphic: true
end
end
list = V2::List.find_by(slug: "people")
=> #<V2::List:0x007fd6e9007f18 id: 97, title: "People"....>
list.listable_items
=> [#<V2::ListableItem:0x007fd6e6497ec8 id: 2633, list_id: 97, listable_id: 100, listable_type: "List",....]
list.listable_items.first.listable
=> #<List:0x007fd6e4185868 id: 100,...>
我认为这是因为ListableItems的listable_type列中的类定义而发生的。当我调用相关记录时,有没有办法让它引用模型的V2版本而不是db列中定义的版本?
添加
def listable_type
"V2::" + super
end
到ListableItem类并没有改变被调用列表的类。
答案 0 :(得分:0)
解决方案是覆盖可列表方法,而不是listable_type方法。可能有更好的方法来做到这一点,但这种方式对我有用。
Module V2
class ListableItem < ListableItem
belongs_to :list, class_name: "V2::List"
belongs_to :listable, polymorphic: true
def listable
("V2::" + listable_type).constantize.find(listable_id)
end
end
end