Topic: how to apply a given condition to all DB accesses in an application?

Hi all,

I have various model classes that have a data_owner_id field, and EVERY TIME I need to access some data from DB for any of these models I need to impose the condition on the data_owner_id (data_owner_id = @current_user.data_owner_id), so that I don't end up mixing data that belongs to user X with data that belongs to user Y.

Both me and my other rails-newbie developper buddy feel that there should be a more DRY way to do this. After all the application is very intense on database access and we end up coding the exact same condition in many many places.

Is there a way to implement this with some kind of filter or callbacks (on SQL select actions) or maybe some observer classes? Help is really appreciated.

Thanks a bunch.

Re: how to apply a given condition to all DB accesses in an application?

Hmmm,  I have a similar situation, and I've never thought to DRY it up,  but I should,  it's getting damp right now!

The tricky part is that you'd need to add a condition to your finds automatically.  I think that means you'll have to intercept your finds and grovel around the arguments,  and manipulate the :conditions hash item.

You'd do this is a psuedo model,  the inherit all your models from that psuedo model.

ROUGHLY, it might look like this

class M < ActiveRecord::Base
  def find(???
     # append "and data_owner_id = @current_user.data_owner_id"  to :conditions hash item
     super(???
  end

class A < M
end

class B < M
end

So any model inherited from the M model will append your extra condition to any finds.

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: how to apply a given condition to all DB accesses in an application?

i've been looking for a solution a bit more and looks like there is a more elegant way than inheriting from a super class (which may or may not be possible depending on other inheritances btw).

It seems to me that overwriting the find method in every model class where i want to impose the data_owner_id condition, and inside putting the following:

with_scope(:find => { :conditions => "data_owner_id = @current_user.data_owner_id" }
super

should do the job. it seems the with_scope method is incredibly powerful for this kind of work we are trying to get done. rails awes again! :-)

Re: how to apply a given condition to all DB accesses in an application?

nice,  yes,  more elegant!  Easier than what I was thinking in particular my case!

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.