Multiple foreign keys referencing the same table in RoR

前端 未结 5 1376
隐瞒了意图╮
隐瞒了意图╮ 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 15:14

    In Rails 5.1 or greater you can do it like this:

    Migration

    create_table(:customers) do |t|
        t.references :address, foreign_key: true
        t.references :address1, foreign_key: { to_table: 'addresses' }
    end
    

    This will create the fields address_id, and address1_id and make the database level references to the addresses table

    Models

    class Customer < ActiveRecord::Base
      belongs_to :address
      belongs_to :address1, class_name: "Address"
    end
    
    class Address < ActiveRecord::Base
      has_many :customers,
      has_many :other_customers, class_name: "Customer", foreign_key: "address1_id"
    end
    

    FactoryBot

    If you uses FactoryBot then your factory might look something like this:

    FactoryBot.define do
      factory :customer do
        address
        association :address1, factory: :address
      end
    end
    

提交回复
热议问题