Complex polymorphic routes


#1

I’ve used polymorphic routes which seem to not be QUITE what most
people mean when they use this term. Most discussions are intended to
handle things like:

/blogs/1/comments
/article/1/comments

where the comments controller handles different parent types.

I have often used something more like this:

/users/1/domains
/domains

Each of these are “scoped” such that if a params[:user_id] is present,
it will scope the domains list, via something like:

def index
load_user
if @user
@domains = @user.domains
else
@domains = Domains.find :all
end
end

private

def load_user
if params[:user_id]
@user = User.find params[:user_id]
end
end

This technique works well for me, even if not QUITE so DRY as I would
like. However, when the paths get more complicated:

/users/1/domains/2/records/3
/domains/2/records/3
/records/3

my technique quickly becomes at best complicated, and at worse
impossible to implement and debug easily. This is mainly because some
operations are ALWAYS scoped (modifying a domain, for instance) while
others are not. I suppose I could just check permissions on each
operation and only scope the index method, as that is the only one I
really want to narrow down data for. Once a user lists their domains,
I don’t care if it is used via the /domains/ prefix directly.
However, this means that permission checking will have to occur, where
by scoping it I manage to avoid having to do a lot of this, as all I
need to do is check if curent_user.id == params[:user_id] or if
current_user is an admin.

The additional scoping for direct operations on a specific item seem
to be most of the problem, as it is mostly unnecessary.

Do others have solutions to this sort of problem that are cleaner than
what I have done, or might end up doing?

Thanks,
–Michael