How to filter model data before rendering in Streamlined

One question that seems to come up a lot on the Streamlined mailing list is how best to filter the records that are displayed in the list view using a certain set of conditions. There are several ways of doing this, but the simplest way is to use Rails’ built-in scoping methods in conjunction with an around filter.

For example, say we have a Task model and a TaskController that is Streamlined-enabled. The TasksController will display a list of all Tasks in the system by default. What if we only want to display Tasks for the currently logged-in user? Something like this would work:

around_filter :scope_by_user, :only => [:list, :index]

def scope_by_user
  Task.find_with_user_scope(current_user) { yield }
end

Once this code is added to the TaskController, any calls to Task#find within the associated actions, views, and helpers will be scoped. Only tasks belonging to the current user will be listed.

What if we still want to perform an unscoped Task#find within an action? We can eliminate the scoping for a specific block of code using the #with_exclusive_scope method. It looks like this:

Task.with_exclusive_scope { code_that_should_not_be_scoped }

And that, folks, is how easy it is to filter lists in Streamlined.