【问题标题】:Has_one through AND has_many through togetherHas_one 通过 AND has_many 通过一起
【发布时间】:2017-05-28 01:51:20
【问题描述】:

您好,我有 3 个型号:

  • 出售
  • 客户
  • 客户地址

-每个销售应该只有一个客户

-每个客户可以有多个销售

效果很好,这里没有问题,但现在我需要这样的东西:

-每个 SALE 应该只有一个 CUSTOMER_ADDRESS

-每个客户可以有多个客户地址


然后,我该怎么做呢?

我可以同时使用 has_one through 和 has_many through 吗?

【问题讨论】:

  • 您希望在哪些模型之间建立关联?我在这里看不到这种需要..

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4


【解决方案1】:

首先在客户和地址之间创建一个 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

这会创建两个独立的关联 - Sale 和 Customer 都与 Address 有不同的关联。

如果您想通过销售加入 Customer to Address 我们可以这样做:

class Customer < ApplicationRecord
  has_many :addresses
  has_many :sales
  has_many :shipping_addresses, through: :sales, 
                               source: :shipping_address
end

【讨论】:

  • 我需要在地址表中创建“shipping_address_id”吗?
  • 否 - shipping_address_idsales 表上。 belongs_to 将外键放在模型表上。将其放在addresses 上意味着可以在一次销售中使用一个地址。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 1970-01-01
  • 2011-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多