Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Active Record Associations in Rails Active Record Associations Variations on Foreign Key Migrations

Owen Abbott
Owen Abbott
4,776 Points

confused about the difference between adding a foreign key and indexing.

I'm new to this site and brand new to programming in general. I'm learning rails development, and when explaining hot to create associations between models, the video says we add a foreign key and also an "index." It says we can function with just foreign keys, but that indexing is faster and standard.

I can conceptualize what a foreign key looks like and how it creates an association, but I'm pretty hazy on what 'indexing' looks like or does.

1 Answer

Jade Steffen
Jade Steffen
1,842 Points

Hey Owen, great question.

It sounds like you know a bit about what Foreign Keys are, but what about indexes? An index is a bit of an optimization tool. It allows the database to search and sort the table on the foreign key ids.

So, if you ask the database for all the Children belong to a given Parent, it will be able to use the foreign key ID as an index into the table. Because it has created an index for parent Id's, much like the index to a book, this information is readily available. The alternative would be for the database to go through every row and see if it's foreign key id matches that parent Id.

Hope that helps, Jade