Forum: Ruby on Rails Finding a nested resource's 'parent' object?

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.
Matt D. (Guest)
on 2009-01-03 18:09
(Received via mailing list)
Say I have this setup:

class Ticket < ActiveRecord::Base
  belongs_to :project

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

How would I go about programatically figuring out that Ticket is
nested under Project?
Matt D. (Guest)
on 2009-01-03 23:42
(Received via mailing list)
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") &&

      # 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

I'm sure it doesn't work in all cases, but I think it gets pretty
This topic is locked and can not be replied to.