class HouseBuyersController < ... def my_method # How could I get here the relevant model name, i.e. "HouseBuyer" ? end end
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With