Rails 4:在子路径中组织Rails模型而不使用命名空间模型吗? [英] Rails 4: organize rails models in sub path without namespacing models?

查看:78
本文介绍了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的一个未解决的问题在这里: 导轨3.2.9和子文件夹中的模型.

An unanswered question for Rails 3 is here: Rails 3.2.9 and models in subfolders.

使用名称空间指定table_name似乎可以正常工作(请参阅 Rails 4 model子文件夹),但是我要在没有命名空间的情况下执行此操作.

Specifying table_name with namespaces seems to work (see Rails 4 model subfolder), but I want to do this without a namespace.

推荐答案

默认情况下,Rails不会将models目录的子文件夹添加到自动加载路径中.这就是为什么它只能找到命名空间模型的原因-命名空间照亮了要查找的子目录.

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.

这篇关于Rails 4:在子路径中组织Rails模型而不使用命名空间模型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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