Rails 4: organize rail models into subpaths without name patterns?

Is it possible to have something like this?

app/models/ app/models/users/user.rb app/models/users/education.rb 

The goal is to better organize the / app / models folder, but without a namespace for the models.

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

It seems that table_name with namespaces is given (see the Rails 4 subdirectory ), but I want to do this without a namespace .

+63
namespaces ruby-on-rails ruby-on-rails-4 subfolder models
Sep 21 '13 at 15:02
source share
1 answer

Yes, it is definitely possible. The only trick is that you need to add the / app / models subdirectories to the download path for Rails. To do this, add the following to /config/application.rb:

 config.autoload_paths += Dir[Rails.root.join("app", "models", "{*/}")] 

Thus, Rails knows that it is necessary to automatically load subfolders of / app / models without the need for any indication of names.

Note If you have a more complex directory / application / models, the method described above for combining all subfolders in / app / models may not work. In this case, you can get around this by being a little more explicit:

 config.autoload_paths += Rails.root.join("app", "models", "<my_subfolder_name>") 

UPDATE for Rails 4.1+

According to Rails 4.1, the application generator does not include config.autoload_paths by default. So, the FYI above applies to config / application.rb.

UPDATE

Autostart path paths fixed in the above code to use {*/} instead of {**} . Be sure to read muichkine's comment for more details on this.

+89
Sep 21 '13 at 18:32
source share



All Articles