Log in




Adding a named_scope based on user preferences

November 26th, 2009 by Thadd Selden

I recently tackled the problem in Blankless of hiding last year’s gift suggestions. The problem is that I wanted to apply a named scope based on the user preferences. Further complicating things, I couldn’t simply refer to that named scope wherever I needed it, because that would have involved a) a lot of repeating myself and b) a lot of hunting through every file for every reference to gifts.

I needed to find a way to do the same thing as adding a default_scope to the model in a before_filter. But, you can’t just do that because it applies to everyone and doesn’t take effect until the model is reloaded.

The solution turned out to be to add a with_scope in an around_filter as shown. This lets every call to the Gift model’s finders be scoped if I need it to be.

Simple, obvious, and doesn’t require changing any existing code, just added two methods.

Comments are closed.