Reputation: 65183
Let's say the controller name is TemplateUserController
whose model class is TemplateUser
.
Now, I could do self.name.tableize.singularize.string_manipulation…
but that seems a little excessive… I was wondering if there was a faster way to get the model name from the controller. Thanks! =D
Upvotes: 2
Views: 2525
Reputation: 79622
@Sam
's solution of controller_name.classify.constantize
works for all controllers, although many like me may have to lookup the doc to realize that 'controller' is not part of the name.
If your controller is to control a model though, you should consider using inherited_resources. You get many benefits, one of which is the method resource_class
:
class TemplateUserController < InheritedResources::Base
resource_class # => TemplateUser
end
Upvotes: 0
Reputation: 83680
params[:controller]
#=> "TemplateUserController"
params[:controller][/.*[^Controller]/]
#=> "TemplateUser"
params[:controller]
#=> "UsersController"
params[:controller][/.*[^Controller]/].singularize
#=> "User"
And yes - in real world there are many of controllers don't refer to model
PS
Istead of params[:controller]
you can use Rails.controller
Upvotes: 0
Reputation: 138210
You probably know that you can't guarantee a 1-to-1 mapping between controllers and models.
However, in the cases where you can, CanCan
is a gem which needs to do the same thing you're after, and it does it like this:
def model_name
params[:controller].sub("Controller", "").underscore.split('/').last.singularize
end
Because there isn't an implied link between model and controller (except by convention), making your own judgements based on the controller name is the only way to go.
Upvotes: 3