开发者

Ruby on Rails 2.3.8: Is there a way to get the controller name from a model?

开发者 https://www.devze.com 2023-03-26 11:35 出处:网络
Like, lets say I have 开发者_开发问答the model called: Vehicle. Is there any command such as Vehicle.controller that would return :vehicles_controller or \"vehicles_controller\" ?Not that I\'m aware o

Like, lets say I have 开发者_开发问答the model called: Vehicle.

Is there any command such as Vehicle.controller that would return :vehicles_controller or "vehicles_controller" ?


Not that I'm aware of, but its easy to create such a helper:

def controllerize(model)
  "#{model.name.tableize}_controller"
end

Better question is why do you want it? Sounds like a bit of a code smell—there aren't a lot of good reasons for your model to know anything about your controllers.


Why? It's routes that determines paths not models.

Making your model aware of routes makes no sense at all. Models are there to deal with business logic and data. Routes are the domain of controllers.

If you have a route defined as resource :vehicles in your routes.rb then you have routes available to you in the form of vehicle_path, vehicles_path etc... to find out what routes you have just run rake routes from your command line in your apps root folder.


It's just a naming convention and good practice that gets you some things for free, for doing it the Rails way, that a controller for User model is often called UsersController. If you keep with a convention, then you can write a method that does that for you. Otherwise, the answer is: "No, sorry".

0

精彩评论

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