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 Build a Simple Ruby on Rails Application Customizing Forms Getting the Latest Changes

Edward Poon
Edward Poon
9,313 Points

What do Indexes do?

What do indexes do? I'm looking at the code for add_user_id_to_questions. The whole code in that file kind of confuses me so can you please explain it to me?

Some questions:

  1. Does add_column: statuses, :user_id, :integer //this just creates a column inside the questions.db called user_id which is integer

  2. add_index :statuses, :user_id // What does add_index do?

  3. remove_column :statuses, :name // just removes name from the questions.db

Glenn Harris
Glenn Harris
7,101 Points

Indexes are basically a way to improve performance of your database queries. If you have a small app it won't make much of a difference, but once your app gets large you have to pay attention to performance.

Here is a good article on indexes: https://tomafro.net/2009/08/using-indexes-in-rails-index-your-associations

"a database index is a data structure that improves the speed of operations on a database table"

  1. Does add_column: statuses, :user_id, :integer //this just creates a column inside the questions.db called user_id which is integer

This is a function to add a column named "user_id" to the statuses table with data type "integer". Here is a list of data types available to you in Rails 4 : http://stackoverflow.com/a/17918118

add_index :statuses, :user_id // What does add_index do? If you read the article above you should have a better idea of what an index does.

remove_column :statuses, :name // just removes name from the questions.db

It removes a column named 'name' from the 'statuses' table.

If you're feeling adventurous you should read about "n+1" queries, which really don't have anything to do with indexes, just database performance: https://www.codemy.net/posts/optimizing-your-rails-app-part-1-n-1-queries