Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.