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

前端 未结 6 2057
别那么骄傲
别那么骄傲 2020-12-22 20:49
class HouseBuyersController < ...
  def my_method
    # How could I get here the relevant model name, i.e. \"HouseBuyer\" ?
  end
end
6条回答
  •  既然无缘
    2020-12-22 21:14

    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
    

提交回复
热议问题