Tim W
Tim W

Reputation: 383

Overriding `inherited` on STI class raises NoMethodError

I have the following classes in my rails 4 app:

class ReceiptDocument < ActiveRecord::Base
  @foo

  self.inheritance_column = :document_type
  has_and_belongs_to_many :donations

  protected

    def self.inherited(subklass)
      subklass.inherit_attributes(@foo)
    end

    def self.inherit_attributes(foo)
      @foo = foo
    end
end

class ReceiptRequest < ReceiptDocument; end
class ReceiptResult < ReceiptDocument; end

The class instance variable @foo is set once at class definition, and should have the same value in all subclasses. I added the inherited override so that value would be accessible from both ReceiptRequest and ReceiptResult.

However, now when I call ReceiptRequest.new, I get:

pry(main)> DonationReceiptRequest.new
NoMethodError: undefined method `[]' for nil:NilClass
from /gems/activerecord-4.1.5/lib/active_record/relation/delegation.rb:9:in `relation_delegate_class'

If I comment out that override, things return to normal. However, I can no longer share that value across all subclasses of ReceiptDocument.

Any insight would be greatly appreciated.

Upvotes: 1

Views: 461

Answers (1)

Tim W
Tim W

Reputation: 383

Finally got this sorted.

The error seemed to be pointing me at some behind the scenes work that ActiveRecord was doing, so I dug in a bit further.

It seems that setting self.inheritance_column most likely overrides the inherited method. Honestly, I'm not sure what work is being done that my override was stomping on. But redefining that method as below fixed the issue:

def self.inherited(subklass)
  super # <--
  subklass.inherit_attributes(@foo)
end

Upvotes: 2

Related Questions