具有多个相关地址的Rails模型

时间:2018-12-01 20:55:35

标签: ruby-on-rails activerecord foreign-keys

我有以下Rails模型:

# Address Model
address_line_1
address_line_2
address_line_3
post_code
country

# Vendor model
name
registered_address_id
billing_address_id
display_address_id

注册地址,账单地址和显示地址应引用地址表中的地址。

所以最终我可以做Vendor.registered_address等。

我对如何进行迁移以及模型上的关系感到困惑,有人能指出我正确的方向吗?

非常感谢

1 个答案:

答案 0 :(得分:1)

您可以在class_name上显式声明belongs_tohas_many上的foreign_keyhas_many

class Vendor < ApplicationModel
  belongs_to :registered_address, class_name: 'Address'
  belongs_to :billing_address, class_name: 'Address'
  belongs_to :display_address, class_name: 'Address'
end

class Address < ApplicationModel
  has_many :registered_addresses, foreign_key: :registered_address_id, class_name: 'Vendor'
  has_many :billing_addresses, foreign_key: :billing_address_id, class_name: 'Vendor'
  has_many :display_addresses, foreign_key: :billing_address_id, class_name: 'Vendor'
end

参考:-

has_many

belongs_to

查询=>

vendor_object.registered_address
vendor_object.billing_address
vendor_object.display_address