开发者

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 se开发者_StackOverflow社区ems a little excessive… I was wondering if there was a faster way to get the model name from the controller. Thanks! =D


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


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.


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


@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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜