Forum: Ruby on Rails Access the 'parent' resource from a nested one?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Carl H. (Guest)
on 2007-06-05 20:21
(Received via mailing list)
Is there a possibility in an action to get the parent controller for
which the nested resource is called? for instance if I have the
following in my routes.rb:

  map.resources :user do |users|
    users.resources :logos

  map.resources :pic do |pics|
    pics.resources :logos

How easy would it be to get the parent? for instance I could call the
following 2 URLs:
http://localhost:3000/pics/#{pic_id}/logos/#{logo_id} and

Can I know which parent I am currently in?

Further explanations follows:

The logo class is a polymorphic class defined as follow:

class Pic < ActiveRecord::Base
   has_one :logo, :as => :logoable

class User < ActiveRecord::Base
   has_one :logo, :as => :logoable

class Logo < FlexImage::Model
  belongs_to :logoable, :polymorphic => true

Now in my logo controller, I want to show the correct logo for the
correct parent controller. The URL would look something like:




in my show action in the logo controller I have something like:

logo = Logo.find(:first, :conditions => {:logoable_type
=> ..., :logoable_id => ...})

logoable_type is either User or Pic. However, I can not see how to get
that value easily. I could play around with the param hash as it will
return either pic_id or user_id. Is there any simpler way to know
which parent the nested ressource is called from?

The above to follow DRY. Is there a way to map back from the action to
the parent controller?

I probably need a bit of REST vocabulary but hopefully it is clear

Gabe da Silveira (Guest)
on 2007-06-05 20:39
(Received via mailing list)
I don't see what would be simpler than using pic_id or user_id (maybe
there is something?).  From those you can generate any kind of setup
you want, just put in a before_filter so it's available to all
actions.  Or do something like:

def pic?

Not sure if there's anything built-in, but I don't see the need for it.

On 6/5/07, Carl H. <removed_email_address@domain.invalid> wrote:
>     pics.resources :logos
> class Logo < FlexImage::Model
> http://localhost:3000/users/#{user_id}/logos/#{size}
> >

Gabe da Silveira
Val (Guest)
on 2007-06-05 20:55
(Received via mailing list)

You can find an approach you can use discussed here

Carl H. (Guest)
on 2007-06-06 14:14
(Received via mailing list)

Thanks for the post, that looks to be exactly what I am looking for. I
will leave any comments if any on the article.

This topic is locked and can not be replied to.