Simulating views in Ruby on Rails

If you want to use views in Ruby on Rails but aren’t using a database that supports them, I’ve created a subclass of ActiveRecord::Base that can simulate selecting from a view in a normal ActiveRecord find.

The extension allows the table names in the from section of queries to be replaced with subqueries specified by ActiveRecord classes. The subqueries can do anything that can be done with a view. ActiveRecords using subqueries can be eager loaded with includes like any normal ActiveRecord. This allows group bys and aggregate functions to be used without having to write a custom find_by_sql method or load in lots of data.

Download the code and view the documentation.

Leave a Reply