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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
2adcab94830cc4abd3610984fbe5225c?d=identicon&s=25 Matt Darby (mdarby)
on 2009-01-03 17:09
(Received via mailing list)
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?
2adcab94830cc4abd3610984fbe5225c?d=identicon&s=25 Matt Darby (mdarby)
on 2009-01-03 22: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") &&
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.
This topic is locked and can not be replied to.