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

问题描述

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

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

想象一下,我们的程序有两个这样的控制器组(比如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


推荐答案

文件名称无关紧要。

有两个相同名称的文件完全可以,例如 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

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

09-18 17:39