views:

51

answers:

3

I'm writing a Rails plugin, and need to be able to dynamically determine which model a controller is associated with. For example, if I have a PeopleController, I need a clean way to determine that the controller handles Person models.

I've had a look through the API and haven't found a method for it.

Is the only way to do this as a regexp combined with some ActiveSupport inflection trickery like singularize?

If so, are there any pitfalls with this approach? What are the edge cases?

+1  A: 

It's only a convention that a controller and model are related, so there is really no way to do it.

What are you trying to do?

Toby Hede
I'm dynamically adding ajax validation methods in the controller. Something like this: `ajax_validates_for :first_name, :last_name`. I guess I'll just require a first parameter that is the model name that the attributes exist for: `ajax_validates_for :person, :first_name, :last_name`. Thanks!
nfm
yeah, that's probably the easiest appraoch
Toby Hede
A: 

Assuming you are following the Rails naming convention for model and controller names, you can do the following to get the model name/class.

# In a controller instance
klass_name = controller_name.camelize.gsub(/Controller$/, '').singularize
klass = klass_name.constantize
KandadaBoggu
A: 

Iam just modifing a litle KandadaBoggu answer to make it more automatic for any instance of the controller.

# In a controller instance
klass_name = self.class.to_s.gsub(/Controller$/, '').singularize
klass = klass_name.constantize
Boris Barroso