多个外键引用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放在地址"表中.
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
您还可以在assoc声明中提供外键和类
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屋!
查看全文