Search code examples
ruby-on-rails-3namespacesruby-on-rails-3.1polymorphic-associations

Namespaced models don't work with polymorphism and I need a workaround


Polymorphic relationships don't work when the models are namespaced in rails 3.1. Here is an example:

class Accounting::Request::Check < ActiveRecord::Base
  has_one :accounting_request, as: :requestable
end

class Accounting::Request < ActiveRecord::Base
  belongs_to :requestable, polymorphic: true
end


cr = Accounting::Request::Check.create!()
cr.create_accounting_request

Results in:

NameError: uninitialized constant Accounting::Request::Check::AccountingRequest

My question is, how can I work around this for the time being before we migrate to rails 5?

One solution I found was to add class_name: '::ClassName' but this doesn't work for me.


Solution

  • Yes, rails does support polymorphism on namespaced models...

    Here is the revised code that makes it work:

    class Accounting::Request < ActiveRecord::Base
      belongs_to :requestable, polymorphic: true
    end
    
    class Accounting::CheckRequest < ActiveRecord::Base
      has_one :accounting_request, as: :requestable, class_name: 'Accounting::Request'
    end
    

    class_name needs to be on the '-able' model, and needs to fully specify the class that contains belongs_to.

    Also not that I'm using has_one here instead of has_many.