Postgres Views in Rails

I ran into something recently where I wanted to access a Postgres view from a Rails 6 application. Lots of ways to do this, but I found a pattern that's really simple and feels right to me:

First, make an abstract class called ApplicationView. It's helpful for semantics, and also because everything inheriting it will be read only.

app/models/application_view.rb:

Then, create a model and have it inherit from ApplicationView :

app/models/search_result.rb:

Create your view as part of a regular Rails migration:

Finally, you can access it like a regular Rails model:

Bonus: if you're using this to build a gin or gist search index like I was, you can easily write a scope to execute the search. Assuming your gin index is on haystack_column:

Access like this:

The benefit of using a scope is that you can chain it to longer and more complex queries.

Boom.

© 2023 | RSS | @omarish