Let’s say you have a
Business
class in Rails..and maybe you want to records mergers, so you want to create a
Merger
class. Normally, when we create a model, we use the
references
type: so rails will automatically create both the
<model>_id
fields and the index:
rails g Merger business:references
In this case though, we don’t want to reference just
business
, we want to reference the two companies merging. While the generator doesn’t have the capability itself, since Rails 5, it’s easy enough. Run the migration with the references you’d like:
rails g Merger business_one:references business_two:references new_name
Then modify the two reference fields in the migration from this:
t.references :business_one, foreign_key: true
t.references :business_two, foreign_key: true
To this:
t.references :business_one, foreign_key: { to_table: 'businesses' }
t.references :business_two, foreign_key: { to_table: 'businesses' }