Rails 5 - Namespacing models

There is a certain cost of complexity involved with "namespacing" your models. Ruby does not actually have true namespaces. Rather it has has modules which provide encapsulation.

Rails and ActiveRecord was designed around placing your application code in the Main object (the global object). While this might seem like a bad practice it is very simple and works well with the convention over configuration approach. It also allows a much simpler autoloading scheme and avoids the need to nest every single file in an additional folder.

Namespacing does have great organizational merits though and lets you avoid collisions. But there are a few minor aches in the backside:

  • table prefixes, having the generated table names like my_app_projects_tasks is really inconvenient when you need to write a custom join.
  • You need to override ActiveModel::Naming so that it does not look for paths like my_app_projects_tasks_path when using the polymorphic route helpers.
  • You need to explicitly set the class_name option when creating associations or override how ActiveRecord resolves constant names.