我有以下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等。
我对如何进行迁移以及模型上的关系感到困惑,有人能指出我正确的方向吗?
非常感谢
答案 0 :(得分:1)
您可以在class_name
上显式声明belongs_to
和has_many
上的foreign_key
和has_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
参考:-
查询=>
vendor_object.registered_address
vendor_object.billing_address
vendor_object.display_address