One of the new features being introduced in Rails 1.1 is ActiveRecord#with_scope. The with_scope functionality lets you wrapper a bunch of calls to Model#find or Model#create with a particular set of conditions. These conditions will always be used, regardless of what additional conditions you call Model#find with. If you want to know more about with_scope you might want to read the author’s article on how it works.
Rails includes the base with_scope and with_exclusive scope functionality, but there is a plugin called scoped_access that gives you a few nice tools to make life easier. The article I mentioned about tells you how to get a hold of it.
I’m using ScopedAccess::Filter in Callbx to enforce different types of security. For example, a user should never be able to see tickets from groups that he does not belong to. Normally I would have to write the conditions to restrict access on every action in the controller. Using a ScopedAccess::Filter I can set the scope for Ticket.find on the entire controller. This frees me to concentrate on the functionality for each action, rather than having to be concerned with the access control while coding the rest of the controller.
class TicketsController < ApplicationController
# limit the scope on all calls to Ticket.find in this controller
around_filter ScopedAccess::Filter.new(Ticket, :group_conditions)
def list
@ticket = Ticket.find(:all, :conditions => "status_code_id < 10")
end
protected
# only show tickets from groups that the user is a member of
def group_conditions
conditions = []
session[:user].groups.each do |group|
conditions << "group_id = '#{group.id}'"
end
return :find => {:conditions => "(#{conditions.join(' OR ')})"}
end
end
Assuming that the logged in user belongs to groups 5 and 17, the SQL generated on that Ticket.find in the list method would be something like:
SELECT * FROM `tickets` WHERE status_code_id < ‘10′ AND (group_id = ‘5′ OR group_id = ‘17′)


