Considerations

Although views are often thought of as “just-in-time” tables, and from Rails’s perspective when creating models, we can treat views just like tables, views are not tables. I began this section stating that a view should be thought of as a named subquery. Let’s take a very simple example and imagine that we defined a view, view_of_movies, which is essentially the same as the movies table itself:

create view view_of_movies as
select * from movies;

The view name, view_of_movies, is now a name for the subquery select * from movies;. If we wanted to do a simple select of all the records in this view, the query would look like this:

select *
  from view_of_movies;

But if we expand to show the subquery, we’re actually doing this:

select *
  from (select *
          from movies);

Now it should become clear that many standard table operations won’t work with views. Some operations that won’t work on views include:

  • Inserting

  • Deleting

  • Updating

  • Referencing from another table

  • Adding constraints

  • Indexing

Although this seems like a long list of things you can’t do, and it is, that’s actually OK. These aren’t disadvantages of views; they’re just not what views are meant for. The word “view” itself implies that they are for looking at, not for modifying.[4]

Let’s examine each of these constraints in turn and see what it means for our Rails application.

Insert, Update, Delete

Attempting to insert, update, or delete on a view triggers a database error. When you need to write data, you must do it against table-backed ...

Get Enterprise 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.