![](/img/trans.png)
[英]Rails association has_many and has_many through on same STI model
[英]Rails association “has_many :through” in the same model
我有兩種模式:公司和業務。 該業務屬於兩家公司(供應商和客戶)。 所以我寫了:
商業模式:
class Business < ActiveRecord::Base
belongs_to :client, :class_name => 'Company'
belongs_to :supplier, :class_name => 'Company'
end
公司型號:
class Company < ActiveRecord::Base
has_many :businesses
has_many :companies, through: :businesses
end
但是我不能使用@ company.companies通過其業務訪問與公司相關的公司。 我怎樣才能做到這一點?
您可能具有一個附加的表BusinessRelationship,該表具有諸如“ relationship_type”之類的屬性,該屬性可以是“ client”或“ supplier”,或者實際上是對RelationshipTypes另一個表的引用。 但這會在一個簡單的數據模型中添加很多表,因此從一開始您可能只想保持簡單:
在公司
has_many :businesses_as_client, class_name: "Business", inverse_of: :client, foreign_key: :client_id, dependent: :destroy
has_many :businesses_as_supplier, class_name: "Business", inverse_of: :supplier, foreign_key: :supplier_id, dependent: :destroy
在業務
def companies
(self.businesses_as_client + self.businesses_as_supplier).collect(&:company)
end
這可能不是很有效,所以您可以執行以下操作:
def companies
Company.where(:id => (self.businesses_as_client.collect(&:supplier_id) + self.businesses_as_supplier.collect(&:client_id)))
end
或類似的命令。 對此進行擴展,您甚至可以在Company中嘗試以下操作:
has_many :companies_as_client, through: :businesses_as_client
has_many :companies_as_supplier, through: businesses_as_supplier
def companies
companies_as_client + companies_as_supplier
end
不過,這可能是一個漫長的嘗試!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.