All Case Studies Design Development Interviews Our Way Project Management

Persistent queries in Ruby on Rails with PostgreSQL

Sometimes you need to save a SQL query or query parameters for the future use. Here's a neat solution thanks to which you won't have any problems with sending a newsletter with custom search fields selected by user.

Sometimes you need to save a SQL query or query parameters for the future use. We need that when a user wants to be updated from time to time about latest filtered changes. For example with a weekly newsletter about all adverts for Honda cars produced between 2000 and 2004.

Query is simple:

 

But how to save it and use it every week?

I want to share this very flexible solution, using PostgreSQL json/hstore type and following gems: searchlight and embedson.

First we should create model:

 

and create a search class:

 

Edit SavedQuery a little:

 

and use it like that:

 

Now you shouldn’t have any problems with sending a newsletter with custom search fields selected by user.

If you know a better solution let me know.

Special thanks to Blaze for inspiration. Take care!

If you're looking for more PostgreSQL resources, take a look at Renewed Life for STI with PostgreSQL JSON type.

Why it is impossible to hire quality engineers in London and how to deal with it
Scaling SaaS
READ ALSO FROM Dev
Read also
Need a successful project?
Estimate project or contact us