How to Specify the Foreign Class for Rails Associations in a Different Namespace

15 June 2017 on . 1 minute to read

Referencing Classes From Another Namespace

Say you’ve got the following classes:

class Foo < ApplicationRecord
end

class Foos::FooBarBazs::Baz < ApplicationRecord
    belongs_to :foo
end

Normally for Rails, we can pass a simple has_many :baz, but for models in a different namespace, you have to specify the class name, so it would look like this:

class Foo < ApplicationRecord
    has_many :baz, class_name: "Foos::FooBarBazs::Baz"
end

The above works great, and is what’s recommended in the official docs. However, it presents a problem when code is refactored and you don’t have sufficient code coverage. To remedy that, do the following:

  • enable eager loading for your test environment
  • use a constant, not a string

Using a Constant

The following don’t work:

  • has_many :baz, class_name: Foos::FooBarBazs::Baz
  • has_many :baz, class: Foos::FooBarBazs::Baz

However, what DOES work is: has_many :baz, class_name: Foos::FooBarBazs::Baz.to_s

Now eager loading will catch any typos made here since that would introduce a NameError: uninitialized constant. Also, we’re working with classed and objects in ruby, not strings, so my opinion is that it looks and reads much nicer as well.


If you enjoy having free time and the peace of mind that a professional is on your side, then you’d love to have me work on your project.

Contact or view a list of available services to see how I’ll make your life better, easier and bring satisfaction back into you running your business.