Kevin K
Kevin K

Reputation: 2227

Add association to existing model using a foreign key

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.

Upvotes: 0

Views: 1297

Answers (1)

Richard Peck
Richard Peck

Reputation: 76784

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

Upvotes: 1

Related Questions