# Complex polymorphic routes

**URL:** <https://www.ruby-forum.com/t/complex-polymorphic-routes/155129>\
**Category:** Rails\
**Created:** [December 8, 2008, 1:28pm UTC](https://www.ruby-forum.com/t/complex-polymorphic-routes/155129 "2008-12-08T13:28:15Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![mgreenly](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/85f322/32.png) [@mgreenly](https://www.ruby-forum.com/u/mgreenly)\
**Post date:** [December 8, 2008, 1:28pm UTC](https://www.ruby-forum.com/t/complex-polymorphic-routes/155129/1 "2008-12-08T13:28:15Z")

</div>

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
