6.9. Summary

Rails has exceptional support for managing databases, although there are times when you still need to manage the underlying database directly. One such case is a legacy database that does not conform to Rails naming conventions. There's a little bit of up-front work, but you can gain nearly all the Rails benefits when working with a legacy database, including associations, testing, and database fixtures.

To improve database performance, you can denormalize certain fields of the database, essentially caching some derived information in your database tables. This mechanism is easy to implement using ActiveRecord callbacks, which allow you to specify arbitrary code to be automatically executed at various points of the ActiveRecord lifecycle.

You can create polymorphic relationships, in which the other end of the relationship could be a member of multiple classes. This is implemented by using a multiple foreign key to represent the ID and type of the foreign object.

Rails provides basic functionality to prevent SQL injection attacks, take advantage of database transactions, and automatically restrict a find call within an association.

Get Professional Ruby on Rails™ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.