[英]Rails associations between clients and sellers - has_many :through or has_and_belongs_to_many
我從一個有產品 , 客戶和銷售商的 rails開始一個項目。 每個賣家都有很多has_many products
。 每個客戶有很多has_many products
。 (就我而言,每個客戶一次只能購買一種產品)。
我想知道誰是我的客戶的賣方以及我的賣方的客戶,知道他們將通過購買一種產品鏈接在一起。
我應該在客戶和賣方之間使用has_and_belongs_to_many
關聯嗎? 或has_many through :products
雙重has_many through :products
,如:
賣方 :
has_many :clients through :products
Belongs_to :products
客戶 :
has_many :sellers through :products
Belongs_to :products
為了避免在product
類中使用兩個belongs_to
,可以這樣做嗎?
class Client < ActiveRecord::Base
has_many :products, as: :productable
has_many :sellers, through: :products
end
class Seller < ActiveRecord::Base
has_many :products, as: :productable
has_many :clients, through: :products
end
class Product < ActiveRecord::Base
belongs_to :productable, polymorphic: true
end
預先感謝您的回答。
我會在這里has_many :through
class Client < ActiveRecord::Base
has_many :products
has_many :sellers, through: :products
end
class Seller < ActiveRecord::Base
has_many :prodcuts
has_many :clients, through: :products
end
class Product < ActiveRecord::Base
belongs_to :client
belongs_to :seller
end
最簡單的經驗法則是,如果需要將關系模型作為獨立實體使用,則應設置has_many:through關系。 如果您不需要對關系模型做任何事情,則設置has_and_belongs_to_many關系可能會更簡單(盡管您需要記住要在數據庫中創建聯接表)。
如果需要在連接模型上進行驗證,回調或其他屬性,則應使用has_many:through。
另請參閱這些指南,以在HABTM
和has_many :through
之間進行選擇has_many :through
我想從另一個角度解決您的問題:讓我們從產品入手。 我認為這將澄清很多事情。
因此,您具有三種模型: Seller, Client
和Product
。
Product
具有賣方和客戶。 在您的模型中,這是這樣的:
class Product
belongs_to :seller
belongs_to :client
end
這意味着在產品表中,我們有一列seller_id
和client_id
。
Afaik產品始終需要兼具兩者。 因此這也意味着您不能在此處使用多態關聯。 至少不是您提出的方式。 如果你寫
belongs_to :productable, polymorphic: true
您將添加字段productable_id
和productable_type to your
Product`模型。 但這只是1個鏈接(因此,無論是賣方還是客戶,但都不是兩者)。 您可以在此處引入一個鏈接表,這樣一個產品可以鏈接到許多“可生產的產品”,但是在您的情況下,我認為這不是重點。 您知道一種產品有一個賣方和一個客戶。
其次,現在已經確定了,您的Product
正是客戶和賣方之間的鏈接表。 因此,您不必引入新的鏈接表,只需使用已有的鏈接表即可。
class Seller
has_many :products
has_many :clients, through: :products
end
class Client
has_many :products
has_many :sellers, through: :products
end
因此,結論是:
has_many :through
因為您已經將鏈接表作為模型。 僅在不關心聯接表(鏈接表)的情況下才使用habtm。 seller_id
和client_id
的明確性,清晰度和可讀性,並且它也更易於管理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.