0

Is there a way to instantiate a namespaced model object from its table name?

eg: Given table school_students, model School::Student, id 30, I could do:

student = get_from_table_name_and_id("school_students", 38)

zsquare
  • 9,916
  • 6
  • 53
  • 87

1 Answers1

0

This implementation should work

def get_from_table_name_and_id(klass, id)
  klass.gsub('_','/').classify.constantize.find(id)
end

an output :

irb(main):004:0> "school_students".gsub('_','/').classify                                                                                                                            
=> "School::Student"

The naming convention on Rails is a namespace is represent by a / in String

shingara
  • 46,608
  • 11
  • 99
  • 105
  • Why it's works with my example so ? You send us valid value or you try with another ? – shingara Feb 21 '12 at 14:36
  • Consider a model like `School::StudentSettings` – zsquare Feb 21 '12 at 14:45
  • Yes its doesn't works because it's impossible to know if you your _ is a Namespace of Class. You can do that but you need test several possibility before and choose the right. But can have more than one possibility. – shingara Feb 21 '12 at 15:10
  • Exactly, which is why I was wondering if there was an other option other than string manipulation. – zsquare Feb 21 '12 at 17:18