简体   繁体   English

Ruby on Rails 2.3.8:有没有办法从模型中获取控制器名称?

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

Like, lets say I have the model called: Vehicle . 就像,假设我有一个名为: Vehicle的模型。
Is there any command such as Vehicle.controller that would return :vehicles_controller or "vehicles_controller" ? 是否有诸如Vehicle.controller命令会返回:vehicles_controller"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. 如果你有一个路线定义为resource :vehicles在你的routes.rb,那么你必须提供给您路线的形式vehicle_pathvehicles_path等..找出你刚才的运行路线rake routes从您的命令行的apps根文件夹。

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. 这只是一个命名约定和良好实践,可以免费获取一些东西,以Rails的方式进行,User模型的控制器通常称为UsersController。 If you keep with a convention, then you can write a method that does that for you. 如果您遵循约定,那么您可以编写一个为您执行此操作的方法。 Otherwise, the answer is: "No, sorry". 否则,答案是:“不,对不起”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM