我有以下协会。 PropertyOwner是属于属性的连接模型,并且多态地属于所有者,在下面的示例中是ForeclosureDefense。一切都运作良好,直到我有has_one:main_property。想法是ForeclosureDefense模型可以有许多属性,但最后一个属性是主要属性:
class ForeclosureDefense < ActiveRecord::Base
has_many :property_owners, as: :owner
has_many :properties, through: :property_owners
has_one :main_property, through: :property_owners, source: :property, order: 'created_at desc'
end
class PropertyOwner < ActiveRecord::Base
belongs_to :property
belongs_to :owner, polymorphic: :true
end
class Property < ActiveRecord::Base
has_many :property_owners
has_many :owners, through: :property_owners
has_many :foreclosure_owners, through: :property_owners, source: :owner, source_type: "ForeclosureDefense"
has_many :folder_owners, through: :property_owners, source: :owner, source_type: "Folder"
end
不幸的是,当我尝试使用has_one:main_property关联时,我收到以下错误:
ActiveRecord :: HasOneThroughCantAssociateThroughCollection:不能有has_one:通过关联'ForeclosureDefense#main_property',其中:通过关联'ForeclosureDefense#property_owners'是一个集合。
我做错了什么?
答案 0 :(得分:-2)
我的解决方案只是将其添加为类级宏:
def main_property
properties.order('created_at desc').first
end