Finding a nested resource's 'parent' object?


#1

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?


#2

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.