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
In Rails 5.1 or greater you can do it like this:
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
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
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