在 RoR 中引用同一个表的多个外键 [英] Multiple foreign keys referencing the same table in RoR
本文介绍了在 RoR 中引用同一个表的多个外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望客户引用两种地址模型,一种用于帐单地址,另一种用于送货地址.据我了解,外键由其名称决定,如_id.显然我不能命名两行 address_id (引用地址表).我该怎么做?
I want a Customer to reference two Address models, one for the billing address and one for the shipping address. As I understand it, the foreign key is determined by its name, as _id. Obviously I can't name two rows address_id (to reference the Address table). How would I do this?
create_table :customers do |t|
t.integer :address_id
t.integer :address_id_1 # how do i make this reference addresses table?
# other attributes not shown
end
推荐答案
这对我来说听起来像是 has_many 关系 - 将 customer_id 放在 Address 表中.
This sounds like a has_many relationship to me - put the customer_id in the Address table instead.
Customer
has_many :addresses
Address
belongs_to :customer
您还可以在关联声明中提供外键和类
You can also provide a foreign key and class in the assoc declaration
Customer
has_one :address
has_one :other_address, foreign_key => "address_id_2", class_name => "Address"
这篇关于在 RoR 中引用同一个表的多个外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文