Skip to content

Instantly share code, notes, and snippets.

@mdarby
Created January 4, 2009 15:51
Show Gist options
  • Save mdarby/43077 to your computer and use it in GitHub Desktop.
Save mdarby/43077 to your computer and use it in GitHub Desktop.
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 child class belongs_to the associated AR Class
pair = hash.detect do |k, v|
k.to_s.ends_with?("_id") && target_klass.columns_hash.has_key?(k.to_s)
end
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment