Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

namespaces - Rails 4: organize rails models in sub path without namespacing models?

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/models folder better, but without having to namespace the models.

An unanswered question for Rails 3 is here: 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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", "{*/}")]

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>")

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.

UPDATE

Fixed autoload path examples in the above code to use {*/} instead of {**}. Be sure to read muichkine's comment for details on this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...