# Finding a nested resource's 'parent' object?

**URL:** <https://www.ruby-forum.com/t/finding-a-nested-resources-parent-object/156825>\
**Category:** Rails\
**Created:** [January 3, 2009, 5:09pm UTC](https://www.ruby-forum.com/t/finding-a-nested-resources-parent-object/156825 "2009-01-03T17:09:49Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![vanderkerkoff](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/v/7feea3/32.png) [@vanderkerkoff](https://www.ruby-forum.com/u/vanderkerkoff)\
**Post date:** [January 3, 2009, 5:09pm UTC](https://www.ruby-forum.com/t/finding-a-nested-resources-parent-object/156825/1 "2009-01-03T17:09:49Z")

</div>

Say I have this setup:

class Ticket \< ActiveRecord::Base  
belongs\_to :project  
end

map.resources :projects do |p|  
p.resources :tickets  
end

How would I go about programatically figuring out that Ticket is  
nested under Project?

---

<div class="post-metadata">

**Author:** ![vanderkerkoff](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/v/7feea3/32.png) [@vanderkerkoff](https://www.ruby-forum.com/u/vanderkerkoff)\
**Post date:** [January 3, 2009, 10:42pm UTC](https://www.ruby-forum.com/t/finding-a-nested-resources-parent-object/156825/2 "2009-01-03T22:42:49Z")

</div>

Future reference:

```
def get_parent_resource(target_klass, path)
  # Convert the requested path into hash form
  hash = ActionController::Routing::Routes.recognize_path

```

(path, :method =\> :get)

```
  # Loop through path keys and see if any end in '_id' and our kid

```

class belongs\_to the associated AR Class  
pair = hash.detect{|k, v| k.to\_s.ends\_with?("\_id") &&  
target\_klass.columns\_hash.has\_key?(k.to\_s)}

```
  # Load up the AR class based on the matching path pair
  klass = pair[0].to_s[0...-3].classify.constantize

  # Find and return the target parent object
  klass.find(pair[1])
end

```

I’m sure it doesn’t work in all cases, but I think it gets pretty  
close.
