I have a Rails app where Users have Memberships to Projects (and other things, polymorphically). Users also have Roles. I want User#projects to work like a normal ActiveRecord find, but I also want administrators to have access to every project.
For a while I've been doing this:
class User < ActiveRecord::Base
has_many :memberships, :dependent => :destroy
def projects
if has_role?(:admin)
Project.find(:all)
else
Project.find(:all, :include => :memberships, :conditions => ["memberships.user_id = ?", id])
end
end
end
class Project < ActiveRecord::Base
has_many :memberships, :as => :member, :dependent => :destroy
end
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :member, :polymorphic => :true
end
But I'd really rather do something like this:
class User < ActiveRecord::Base
has_many :memberships, :dependent => :destroy
has_many :projects, :through => :memberships, :source => :member, :source_type => "Project"
end
so that I can use named_scope more regularly (e.g. 'alfred.projects.recent.active'). The
This works if you add new Memberships for admins automatically, but it quickly gets out of hand.
I want to keep the User#projects interface. What's the right track here?
Many thanks.