0

I have a database with tables containers and ports.

The containers table has two columns pol_id and pod_id that both point to the ports table. The ports table has an id column.

I have tried using belongs_to / references inside the migration but it does not provide such flexibility.

Also, I am a bit puzzled at configuring the models for this.

Noman Ur Rehman
  • 6,707
  • 3
  • 24
  • 39

1 Answers1

0

You can use the foreign_key option when creating the migration to customize the foreign key:

t.references(:pol, foreign_key: { to_table: :ports })

In your model you need to tell ActiveRecord what class the association points to:

class Container
  belongs_to :pol, class_name: "Port"
end

You also need to provide the foreign key when creating the inverse association:

class Port
   has_many :containers_as_pol, class_name: "Container", foreign_key: "pol_id"
end
max
  • 96,212
  • 14
  • 104
  • 165
  • Note that the belongs_to in migrations is just an alias for references so the same applies. – max Jul 01 '17 at 15:01