Reputation: 2227
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
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