gpt4 book ai didi

ruby-on-rails - 不能有 has_one :through association ' where the :through association is a collection

转载 作者:行者123 更新时间:2023-12-01 14:59:39 28 4
gpt4 key购买 nike

我有以下关联。 PropertyOwner 是一个连接模型,它属于一个属性(property),多态地属于一个所有者,在下面的例子中是一个 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 :through 关联“ForeclosureDefense#main_property”,其中 :through 关联“ForeclosureDefense#property_owners”是一个集合。

我究竟做错了什么?

最佳答案

我的解决方案只是将其添加为类级宏:

def main_property
properties.order('created_at desc').first
end

关于ruby-on-rails - 不能有 has_one :through association ' where the :through association is a collection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26408781/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com