我想实现以下目标:
class Document < ActiveRecord::Base
has_one :number, as: numberable, through: typeable #<- This relation is the thing I want to have but doesn't work like this (and many other ways I tried)
belongs_to :typeable, polymorphic: true
end
# Example Document Type
class Order < ActiveRecord::Base
has_one :number, as: :numberable
has_one :document, as: :typeable
end
# Number
class DocumentTypeNumber < ActiveRecord::Base
belongs_to :numberable, polymorphic: true
end
由于typeable和numberable将包含相等的记录,我可以在numberable.id = typeable.id和numberable.type = typeable.type 上执行左连接。但是我无法使用rails has_one关系(我想我试图将其滥用到很难)这样工作。所以我的问题是,用上面的数据模型实现以下的最佳方法是什么:
Document.eager_load(:number)
Document.find(1).number
# Or:
Document.eager_load(typeable: { :number })
Document.find(1).typeable.number