The database is a vital component to a Rails website. Every single visit to Rails can cause one, two, or even a few hundred database queries to run. Multiply this by the number of visitors per day and the number of pages each visitor looks at and you can quickly see that database optimization is very important to hosting Rails websites.
1. Reduce the number of queries you run
An easy way to keep your Rails database optimized is to reduce the number of queries it uses. If you can remove code that isn't necessary or do something in one query instead of two queries, you can very quickly improve your site's response time. Rails even makes this easy by giving you the "include" option in ActiveRecord.
2. Database indexes
Having proper database indexes for your tables will really help performance when searching, sorting, and grouping. By default Rails will add indexes to primary keys but you will want to add more indexes by hand. I add indexes to all foreign keys, type columns, and columns that I search on. For example if you search on a username column a lot, add an index to it.
3. Optimize your Rails database queries with ActiveRecord
Rails is developed to make it easy to program for and tries to be as efficient as possible. The Rails database library, ActiveRecord, has many options you can set to improve specific queries. Optimizing individual queries can be a difficult and time-consuming process but typically yields the best performance gains.
4. Hand optimize your SQL queries
Rails makes assumptions about how your site's data is composed of but sometimes the database queries it generates are too complex and need to be improved. First thing you should do is to use the SQL EXPLAIN command to see which queries are slow and why they are slow. Then you can rewrite those queries with raw SQL statements, bypassing the ActiveRecord system Rails uses.
Author Resource:
I didn't address this issue but the actual rails web host you are using plays an important role in your database performance. You want a host that is easy to get started with but can also help you scale up your site as you get more and more traffic. I recommend hosting Rails on Dreamhost , they are inexpensive to get started with and have great support for handling large traffic sites.