Multiple foreign keys referencing the same table in RoR

前端 未结 5 1377
隐瞒了意图╮
隐瞒了意图╮ 2020-12-12 14:13

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 na

5条回答
  •  爱一瞬间的悲伤
    2020-12-12 14:57

    I figured out how to do it thanks to Toby:

    class Address < ActiveRecord::Base
      has_many :customers
    end
    class Customer < ActiveRecord::Base
      belongs_to :billing_address, :class_name => 'Address', :foreign_key => 'billing_address_id'
      belongs_to :shipping_address, :class_name => 'Address', :foreign_key => 'shipping_address_id'
    end

    The customers table includes shipping_address_id and billing_address_id columns.

    This is essentially a has_two relationship. I found this thread helpful as well.

提交回复
热议问题