When it comes to using database views then most of us think that it is difficult to use them with Rails or we may not be able to use ActiveRecord with it. Since I experimented with it in the past so I thought why not share it with you folks.
There are several situations when we would like to use database views with our Rails application like:
If we have a complex SQL query that we don’t want to code in your Rails app due to performance related or any other issues.
When our database guys have already spent a great amount of time writing useful views that can be used in the current app
When we have some repeated query to run in every select statement to fetch data from every table. For instance
Select * from table_name where created_on < today;
In that case we would prefer to have a view with this query and call that view.
In all the above situations, it is pretty easy to use our database views with Rails.
Simply create your model as you would for a table and it will work fine just like your model for a database table.
Interesting thing is, apart from viewing data using views I can even update, delete and insert data in my database tables using my views with all those ActiveRecord/ORM niceties (in Sybase) as long as each database view consists of only one table. If you are using more than one table in your database views then you can only view data but cannot do delete, update and insert operation.
I think this is really useful if we have a database that do not conform to Rails conventions but we would like to follow those conventions without changing the current database if other applications depend on it as well. Simply create views for each table in the database and use those views for our models instead of actual tables.
Those single table views (in other words updatable views) will allow us to follow Rails database conventions without changing our existing database tables while also keeping our database guys happy ;o)
NOTE: I have tried updatable views only with Sybase and would love to know about your experience with other databases.