NullVoxPopuli
NullVoxPopuli

Reputation: 65183

Ruby on Rails: How do I get the Model name from inside the Controller?

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

Answers (4)

Marc-André Lafortune
Marc-André Lafortune

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

Sam Ruby
Sam Ruby

Reputation: 4340

A more direct way to do this: controller_name.classify.

Upvotes: 5

fl00r
fl00r

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

Gareth
Gareth

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

Related Questions