Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How to get the model class name based on the controller class name?

class HouseBuyersController < ...   def my_method     # How could I get here the relevant model name, i.e. "HouseBuyer" ?   end end 
like image 618
Misha Moroshko Avatar asked Feb 02 '11 01:02

Misha Moroshko


2 Answers

This will do it:

class HouseBuyersController < ApplicationController    def index     @model_name = controller_name.classify   end  end 

This is often needed when abstracting controller actions:

class HouseBuyersController < ApplicationController    def index     # Equivalent of @house_buyers = HouseBuyer.find(:all)     objects = controller_name.classify.constantize.find(:all)     instance_variable_set("@#{controller_name}", objects)   end  end 
like image 198
malclocke Avatar answered Oct 13 '22 12:10

malclocke


If your controller and model are in the same namespace, then what you want is

controller_path.classify 

controller_path gives you the namespace; controller_name doesn't.

For example, if your controller is

Admin::RolesController 

then:

controller_path.classify # "Admin::Role" # CORRECT controller_name.classify # "Role"        # INCORRECT 
like image 30
Matt Avatar answered Oct 13 '22 14:10

Matt