0

Say you have these two models

rails generate model User
rails generate model Car

Now I want to add an associations so that the models acquire the form

class User < ActiveRecord::Base
  has_many :cars
en
class Car < ActiveRecord::Base
  belongs_to :driver, foreign_key: "driver_id", class_name: "User"
end

What will my migrations look like to add the proper column to car? Should it be a column named driver_id or user_id?

This is a variation on this question.

Community
  • 1
  • 1
Kevin K
  • 2,191
  • 2
  • 28
  • 41

1 Answers1

1

When you use different foriegn_keys in your associations, you have to remember these associations will only use the foreign_key you provide

--

This means if you're looking to use this association:

belongs_to :driver, foreign_key: "driver_id", class_name: "User"

The migration / table will look like this:

add_column :cars, :driver_id, :integer
Richard Peck
  • 76,116
  • 9
  • 93
  • 147