Backo
Backo

Reputation: 18871

Retrieve the controller name from a class name

I am using Ruby on Rails 3.0.7 and I would like to retrieve a controller name given a class name. That is, I have

Articles::Category

and I would like to retrieve

articles/categories

I would like to retrieve the controller name inside a view file not related to the Articles::Categories controller.

How can I do that (possibly using some Ruby on Rails core method)?

Upvotes: 4

Views: 5752

Answers (5)

Matt
Matt

Reputation: 20776

Instead of underscore.pluralize just use tableize:

ActiveRecord::Base.name.tableize
=> "active_record/bases"

Upvotes: 0

Christoph Petschnig
Christoph Petschnig

Reputation: 4147

Articles::Category.name.underscore.pluralize
=> "articles/categories"

As mentioned by many others, there is no special method for that. But as long as you followed Rails conventions, this approach will take you far.

Upvotes: 12

Ray Baxter
Ray Baxter

Reputation: 3200

Assuming that you really meant Articles::CategoriesController then Articles::CategoriesController.controller_path will give you what you want.

Update The question is, given the name of a Rails Model, how do you get the name of the associated controller?

The answer to that question is, you can't. There is not a one-to-one mapping from the model name to the controller name. The User model could be controlled by the users_controller.rb and/or admin/users_controller.rb or not have an associated controller at all. You can certainly guess at some likely possibilities based on Rails conventions but you can't know.

Upvotes: 0

gunn
gunn

Reputation: 9165

Articles::Categories.name.underscore #=> articles/categories

And it underscores camelcased words to so that:

RailsAdmin::ApplicationHelper.name.underscore #=> rails_admin/application_helper

Upvotes: 1

Spyros
Spyros

Reputation: 48606

To get the controller name, say inside your view, you can do :

<%= controller.controller_name %>

To get the name of a class, say User, if you have a user object named user :

user.class.to_s 

Other than that, i don't think there's a correlation between a controller and a model, that can give you the controller name from a class name, because they are different things. You can maybe create a hash like {:controller => 'class_name'} and map those yourself.

Upvotes: 4

Related Questions