Rails 4:在没有命名空间模型的子路径中组织 Rails 模型?
有可能有这样的东西吗?
Would it be possible to have something like this?
app/models/
app/models/users/user.rb
app/models/users/education.rb
目标是更好地组织 /app/models 文件夹,但不必为模型命名.
The goal is to organize the /app/models folder better, but without having to namespace the models.
Rails 3 的一个未回答的问题在这里:Rails 3.2.9 和子文件夹中的模型.
An unanswered question for Rails 3 is here: Rails 3.2.9 and models in subfolders.
使用命名空间指定 table_name 似乎有效(请参阅 Rails 4 模型子文件夹),但是 我想在没有命名空间的情况下执行此操作.
Specifying table_name with namespaces seems to work (see Rails 4 model subfolder), but I want to do this without a namespace.
默认情况下,Rails 不会将模型目录的子文件夹添加到自动加载路径.这就是为什么它只能找到命名空间模型——命名空间阐明了要查找的子目录.
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.
要将 app/models 的所有子文件夹添加到自动加载路径,请将以下内容添加到 config/application.rb:
To add all subfolders of app/models to the autoload path, add the following to config/application.rb:
config.autoload_paths += Dir[Rails.root.join("app", "models", "{*/}")]
或者,如果您有一个更复杂的 app/models 目录,上述将 app/models 的所有子文件夹组合在一起的方法可能无法正常工作.在这种情况下,您可以通过更明确一点并仅添加您指定的子文件夹来解决此问题:
Or, if you have a more complex app/models directory, the above method of globing together all subfolders of app/models may 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:
config.autoload_paths += Rails.root.join("app", "models", "<my_subfolder_name1>")
config.autoload_paths += Rails.root.join("app", "models", "<my_subfolder_name2>")
Rails 4.1+ 更新
从 Rails 4.1 开始,应用程序生成器默认不包含 config.autoload_paths
.所以,请注意上述内容确实属于 config/application.rb.
UPDATE for Rails 4.1+
As of Rails 4.1, the app generator doesn't include config.autoload_paths
by default. So, note that the above really does belong in config/application.rb.
修复了上述代码中的自动加载路径示例以使用 {*/}
而不是 {**}
.请务必阅读 muichkine 的评论 了解详情.
Fixed autoload path examples in the above code to use {*/}
instead of {**}
. Be sure to read muichkine's comment for details on this.