Ruby-on-rails Rails 4:在没有命名空间模型的子路径中组织 Rails 模型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18934115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails 4: organize rails models in sub path without namespacing models?
提问by Rubytastic
Would it be possible to have something like this?
有可能有这样的东西吗?
app/models/
app/models/users/user.rb
app/models/users/education.rb
The goal is to organize the /app/modelsfolder better, but without having to namespace the models.
目标是更好地组织/app/models文件夹,但不必为模型命名。
An unanswered question for Rails 3 is here: Rails 3.2.9 and models in subfolders.
Rails 3 的一个悬而未决的问题在这里: Rails 3.2.9 and models in subfolders。
Specifying table_name with namespaces seems to work (see Rails 4 model subfolder), but I want to do this without a namespace.
使用命名空间指定 table_name 似乎有效(请参阅Rails 4 模型子文件夹),但我想在没有命名空间的情况下执行此操作。
回答by pdobb
By default, Rails doesn't add subfolders of the models directory to the autoload path. Which is why it can only find namespaced models -- the namespace illuminates the subdirectory to look in.
默认情况下,Rails 不会将模型目录的子文件夹添加到自动加载路径。这就是为什么它只能找到命名空间模型——命名空间阐明了要查找的子目录。
To add all subfolders of app/modelsto the autoload path, add the following to config/application.rb:
要将app/models 的所有子文件夹添加到自动加载路径,请将以下内容添加到config/application.rb:
config.autoload_paths += Dir[Rails.root.join("app", "models", "{*/}")]
Or, if you have a more complex app/modelsdirectory, the above method of globing together all subfolders of app/modelsmay not work properly. In which case, you can get around this by being a little more explicit and only adding the subfolders that you specify:
或者,如果您有一个更复杂的app/models目录,则上述将app/models 的所有子文件夹组合在一起的方法可能无法正常工作。在这种情况下,您可以通过更明确一点并仅添加您指定的子文件夹来解决此问题:
config.autoload_paths += Rails.root.join("app", "models", "<my_subfolder_name1>")
config.autoload_paths += Rails.root.join("app", "models", "<my_subfolder_name2>")
UPDATE for Rails 4.1+
Rails 4.1+ 更新
As of Rails 4.1, the app generator doesn't include config.autoload_pathsby default. So, note that the above really does belong in config/application.rb.
从 Rails 4.1 开始,应用程序生成器config.autoload_paths默认不包含在内。所以,请注意,上面的内容确实属于config/application.rb。
UPDATE
更新
Fixed autoload path examples in the above code to use {*/}instead of {**}. Be sure to read muichkine's commentfor details on this.
在上面的代码固定自动加载路径的例子使用{*/}的代替{**}。请务必阅读muichkine 的评论以了解有关此内容的详细信息。

