Ruby Active Record Associations in Rails Active Record Associations Has Many Associations

How did models knew that "post_id" in comments model will be the foreign key for the primary key "id" in posts model ?

How did models knew that "post_id" in comments model will be the foreign key for the primary key "id" in posts model ?

is it from adding index when we were adding the "post_id" column to comments model ? or ... ?

1 Answer

Jay McGavren
STAFF
Jay McGavren
Treehouse Teacher

From the ActiveRecord documentation on belongs_to:

By default this is guessed to be the name of the association with an _id suffix. So a class that defines a belongs_to :person association will use "person_id” as the default :foreign_key.

If you want to use a different column name as the foreign key, you can pass the foreign_key when you call the belongs_to method.