Serializing and scoping Mongoid criteria

So, while working on a project, I ran into a snag. I’ve got a partial which renders a list of images, and I want that partial to be auto-updated. That partial is used in multiple controllers and actions and is passed lots of different arbitrary data sets. How do you manage auto-updating that partial, and additionally, gain the ability to access that list’s criteria in other areas? I also have a ‘grid view’ of the images – I want to be able to pass my image list along to that and have it render it, but I still want to paginate (and on the grid view, pagination is done by different amounts).

Mongoid lets us build (much as ARel lets us do in ActiveRecord) criteria up, which consist of a few things, but mostly a selector (“Which records?”) and options (“How do you want them?”). So the answer is actually pretty straightforward – we serialize these objects and then use them to build our base criteria, on which we can then do pagination. Neat, right?

So, how do we do this? Easy, actually.

Essentially we need a method for setting scope, and one for loading it. So let’s define those methods and set it up.

Okay – now we’ve got a scope key stored in our @list_scope instance variable. This refers to an entry in our cache store (in our case, Redis) which holds info on how to reconstruct that criteria. We’re tagging along a few special parameters, too, not just the essentials.

Now that we’ve got this we can refer to that scope where we need to – for instance, in links to other controllers, or in data- attributes to specify regions to automatically reload on the page.

Pulling out a criteria (and any other data we might want) is trivial at this stage. This technique can let you throw arbitrary-complexity queries around in userspace, allowing for clever client-side stuff and a smoother workflow for many applications and users. Give it a shot and have a play with what you can do!