Search code examples
ruby-on-rails-3sti

Rails and STI with has_many doesn't recognize subclass


I have the following:

class Series < ActiveRecord::Base
    has_many :components
end

class Component < ActiveRecord::Base
  belongs_to :series
end

class Base < Component
end
class Shaft < Component
end
class Capital < Component
end

So, a Series has many Components, and a Component belongs to a Series. I use STI to subclass Components into Bases, Shafts and Capitals.

However, when I want to list the components belonging to a series, by component type I get

 s.bases
 NoMethodError: undefined method `bases' for #<Series:0x007fe30e24d198

Perhaps I am missing something really basic about Rails and STI. Should this work? (note, I do have a type column on the table, and it has the classes in it. I have 'required' the subclass definitions in an initializer file, as suggested elsewhere on Stackoverflow)


Solution

  • No it shouldn't. You've said has_many :components so you get a components association which will contain all the components (and subclasses) associated with the object.

    It doesn't magically add associations restricted to the various subclasses but you can add a separate bases one if you want