Occasional encounters with Ruby on Rails.

Thursday, February 22, 2007

Nested Polymorphic Active Resources (Revisited)


Quick update on my previous post regarding Nested Polymorphic Active Resources. I found that in some cases it was really handy to have the find_polymorphic_resource method in actions other than index and create. When I tried making the call, however, it didn't work. It turns out that the logic at the end of the find_polymorphic_type_and_id of the PolymorphicResource module was flawed.

Originally the method closed with:

sections.pop

That works great for nested resources that need to know their owner for index and create because there is only one element in the sections array. It does not work at all if you're using one of the other RESTful methods like show or edit. In those cases both the owner and the child show up on the url as

GET /owner/:owner_id/child/:child_id

To work around this I've simply changed the last line of the find_polymorphic_type_and_id method to read as follows:

sections.first

The logic behind this is simple. When you have only one element in the sections array (index/create) then you return the one object -- that's the parent and the same thing returned by sections.pop. When you have a nested path (show/edit) it's the first element in the array that has the parent.

This clearly has its limitations, but they are the same limitations as those imposed by the original solution -- it only supports one level of nesting. If you wanted to support multiple levels of nesting you could probably just index the sections array more explicity. For example, the immediate parent could be found at

sections[sections.length-2]

Okay, I didn't realize that last bit was quite so simple. I was lazy and went for the quick way out. Time to go up date my module...

No comments: