在两个不同的目录中具有相同的控制器名称 [英] Same controller name in two different directories

查看:160
本文介绍了在两个不同的目录中具有相同的控制器名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

From'Agile Web Development with Rails 4'pag.272。

From 'Agile Web Development with Rails 4' pag.272.


如果传入请求有
a controller named say)admin / book,Rails将在目录app / controllers / admin中查找名为
book_controller的控制器。也就是说,
控制器名称的最后部分将总是解析为一个名为name_controller.rb的文件,任何
引导路径信息将用于浏览子目录,
从应用程序开始/ controllers目录。

If an incoming request has a controller named (say) admin/book, Rails will look for the controller called book_controller in the directory app/controllers/admin. That is, the final part of the controller name will always resolve to a file called name_controller.rb, and any leading path information will be used to navigate through subdirectories, starting in the app/controllers directory.

想象一下,我们的程序有两个这样的控制器组(比如admin / xxx
和content / xxx)书控制器。在
app / controllers的管理和内容子目录中有一个名为book_controller.rb的
文件。这两个控制器文件将定义一个名为BookController的类。如果Rails没有采取进一步的措施,这两个类会发生冲突。
为了解决这个问题,Rails假定
目录app / controllers的子目录中的控制器是以子目录命名的Ruby模块。

Imagine that our program has two such groups of controllers (say, admin/xxx and content/xxx) and that both groups define a book controller. There’d be a file called book_controller.rb in both the admin and content subdirectories of app/controllers. Both of these controller files would define a class named BookController. If Rails took no further steps, these two classes would clash. To deal with this, Rails assumes that controllers in subdirectories of the directory app/controllers are in Ruby modules named after the subdirectory.

我的问题是:两个book_controller.rb文件如何冲突?

我有两个不同的URL:.... / admin / book和.... / content /书,他们怎么能冲突?在上一段中,它明确表示

My question is: how could the two book_controller.rb files clash?
I have two different URLs: ..../admin/book and ..../content/book, how can they clash? In the previous paragraph it explicit says


[..]任何前导路径信息将用于浏览子目录,从应用程序/控制器目录

[..] any leading path information will be used to navigate through subdirectories, starting in the app/controllers directory


推荐答案

文件名称无关紧要。

有两个相同名称的文件完全可以,例如 controllers / admin / books_controller.rb controllers / books_controller.rb

It's totally okay to have two files with identical names, like controllers/admin/books_controller.rb, and controllers/books_controller.rb.

但是,不同。您可以添加命名空间以区分它们。例如

However, the class names inside those controller should be different. You can add namespace to differentiate them. For example

class Admin::BooksController

class BooksController

这篇关于在两个不同的目录中具有相同的控制器名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆