Benjamin Curtis

Speculations on Web Development

Scoping Finds in Your Controllers

| Comments

Here’s a fun one that’s been discussed a little bit here and there. One scenario I encounter pretty regularly is needing to have two different ways to load data from a controller action:

  1. Load all data (a list of orders, let’s say) when the user loading the action is an admin
  2. Load a subset of data (a list of just one user’s orders) when the user loading the action is not an admin

There are a few ways you can handle this scenario, but here’s my favorite way (for the time being, at least):

class OrdersController < ApplicationController def index @orders = order_finder.find(:all, :order => 'name') end protected def order_finder current_user.admin? ? Order : current_user.orders end end

This is a simplified snippet, but it demonstrates an easy way to change the data being pulled out based on who is using the application. And for no extra charge you can still keep your controller code lean and mean. :)

Comments