[英]Has_one through AND has_many through together
Hello i have 3 models: 您好我有3个模型:
-Each SALE should have only one CUSTOMER -每笔销售应只有一名客户
-Each CUSTOMER can have more than one SALE -每个客户可以有多个销售
That works great, there's no problem here, but now i need something like this: 效果很好,这里没有问题,但是现在我需要这样的东西:
-Each SALE should have only one CUSTOMER_ADDRESS -每个SALE应该只有一个CUSTOMER_ADDRESS
-Each CUSTOMER can have more than one CUSTOMER_ADDRESS -每个CUSTOMER可以有多个CUSTOMER_ADDRESS
And then, how can i do this? 然后,我该怎么做?
Can i use has_one through and has_many through together? 我可以同时使用has_one和has_many吗?
Start by creating a 1-n association between Customer and Address: 首先在客户和地址之间创建1-n关联:
class Customer < ApplicationRecord
has_many :addresses
end
class Address < ApplicationRecord
belongs_to :customer
end
Then add the order model and setup the associations: 然后添加订单模型并设置关联:
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
This creates two seperate associations - both Sale and Customer have distinct associations to Address. 这将创建两个单独的关联-销售和客户对地址都有不同的关联。
If you want to join Customer to Address via sale we can do: 如果您想通过销售加入客户以致地址,我们可以:
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.