[英]Has_one through AND has_many through together
您好我有3個模型:
-每筆銷售應只有一名客戶
-每個客戶可以有多個銷售
效果很好,這里沒有問題,但是現在我需要這樣的東西:
-每個SALE應該只有一個CUSTOMER_ADDRESS
-每個CUSTOMER可以有多個CUSTOMER_ADDRESS
然后,我該怎么做?
我可以同時使用has_one和has_many嗎?
首先在客戶和地址之間創建1-n關聯:
class Customer < ApplicationRecord
has_many :addresses
end
class Address < ApplicationRecord
belongs_to :customer
end
然后添加訂單模型並設置關聯:
class Customer < ApplicationRecord
has_many :addresses
has_many :sales
end
class Address < ApplicationRecord
belongs_to :customer
has_many :sales_as_shipping_address, class_name: 'Sale',
foreign_key: 'shipping_address_id'
end
class Sale < ApplicationRecord
belongs_to :customer
belongs_to :shipping_address, class_name: 'Address'
end
這將創建兩個單獨的關聯-銷售和客戶對地址都有不同的關聯。
如果您想通過銷售加入客戶以致地址,我們可以:
class Customer < ApplicationRecord
has_many :addresses
has_many :sales
has_many :shipping_addresses, through: :sales,
source: :shipping_address
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.