Nested Resource with two different parent controllers

I’m trying to figure out how to created nested resources for a
controller that can have two different “parent” controllers. For
example:

Take the following models:

  • Business
  • Event
  • Comment (business_id, event_id, etc…

A Comment can be associated with either a business or an event. An
event can be associated with a business, but does not have to be.

I can obviously set up the standard REST routes for a Comment. but I’d
like to setup nested resources but can’t figure out how to get it to
work for both an Event and a Business.

Ideally, I’d like the following routes:

/events/10/comments
/events/10/comments/new
/events/10/comments/2

/businesses/23/comments
/businesses/23/comments/new
/businesses/23/comments/2

Can this be accomplished with just one Comments controller? If so, how
do you set it up? As well, I’d like some fields on the Comments[new|
edit] form to change depending on whether it’s being created inside a
business or inside an event.

I though about creating two additional controllers that subclass off
of Controller and calling them BusinessComments and EventsComments,
but this doesn’t seem like a Rails-way of doing it.

(Note that I can easily change my db schema if there is a better way
to model these relationships.)

Thanks for any help,
Sincerely,
Kenny

On 12/14/07, Kenny C [email protected] wrote:

A Comment can be associated with either a business or an event. An
/events/10/comments/2
I though about creating two additional controllers that subclass off
of Controller and calling them BusinessComments and EventsComments,
but this doesn’t seem like a Rails-way of doing it.

I may be wrong, but I think that this is the Rails way to do it.
Doing otherwise would lead to an overly complex controller which needs
to differentiate the urls.

I think you want to set up the routing something like this:

map.resources :events do | event |
event.resources :comments, :controller => :event_comments
end

map.resources :businesses do | business |
business.resources :comments, :controller => :business_comments
end

Of course, I could be wrong.

Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

Best to checkout the resource_controller plugin. It deals with exactly
what you are trying to do:

http://jamesgolick.com/resource_controller/rdoc/index.html

See Polymorphic Resources.

HTH,
Nicholas