Same controller name in two different directories

北城以北 提交于 2019-12-12 01:46:13

问题


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

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.

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.

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


回答1:


The file names do not matter. What matter are the constant names.

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



回答2:


Imagine the filepaths like this

../app/controllers/admin/book_controller.rb

&&

../app/controllers/content/book_controller.rb

Rails uses convention over configuration: http://en.wikipedia.org/wiki/Convention_over_configuration

Like it states in the last paragraph

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.

Someone please correct me if I'm wrong but rails would look for models named admin.rb and content.rb



来源:https://stackoverflow.com/questions/20162628/same-controller-name-in-two-different-directories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!