![](/img/trans.png)
[英]Different instances of the same model (multiple has_many through associations)
[英]Multiple associations in the has_many “through” model
我有一個“ Products
和Parts
模型,每個模型都有多個上載,而且都是多態的。 我是否可以使用單個ItemUpload
模型來處理產品/零件與上載之間的關聯,還是需要將它們分開? 我想嘗試一下自己,但不想在線下造成任何潛在的麻煩! 請注意,我知道我需要做source:
和source_type:
東西來清理has_many
的多態關聯,但想在繼續之前先闡明這一點。 當前型號:
class Product < ApplicationRecord
has_many :uploads, as: :uploadable, dependent: :destroy
end
class Part < ApplicationRecord
has_many :uploads, as: :uploadable, dependent: :destroy
end
class Upload < ApplicationRecord
belongs_to :uploadable, polymorphic: true
end
我理想的情況是:
Class ItemUpload < ApplicationRecord
belongs_to :product, optional: true
belongs_to :part, optional: true
belongs_to :upload
end
可以嗎?還是需要一個單獨的ProductUpload
和PartUpload
模型?
我本以為您的關聯會更像:
class Product < ApplicationRecord
has_many :item_uploads, as: :itemable, dependent: :destroy
has_many :uploads, through: :item_uploads
end
class Part < ApplicationRecord
has_many :item_uploads, as: :itemable, dependent: :destroy
has_many :uploads, through: :item_uploads
end
class Upload < ApplicationRecord
has_many :item_uploads
has_many :products, through: :item_uploads, source: :itemable, source_type: 'Product'
has_many :parts, through: :item_uploads, source: :itemable, source_type: 'Part'
end
Class ItemUpload < ApplicationRecord
belongs_to :itemable, polymorphic: true
belongs_to :upload
end
那應該允許你做:
product.uploads
part.uploads
upload.products
upload.parts
順便說一句,參考您提供的鏈接:
Upload ≈ User
ItemUpload ≈ Membership
Product, Part ≈ Project, Group
上面是鏈接文章中的模式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.