Rails 和带有 has_many 的 STI 无法识别子类
我有以下内容:
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
所以,一个系列有许多组件,一个组件属于一个系列。 我使用 STI 将组件子类为底座、轴和首都。
然而,当我想按组件类型列出属于某个系列的组件时,我得到
s.bases
NoMethodError: undefined method `bases' for #<Series:0x007fe30e24d198
Maybe I ammissing 关于 Rails 和 STI 的一些非常基本的东西。这应该有效吗? (注意,我的表上确实有一个类型列,其中包含类。我“需要”初始化程序文件中的子类定义,如 Stackoverflow 上其他地方所建议的那样)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,不应该。您已经说过
has_many :components
这样您就得到了一个组件关联,它将包含与该对象关联的所有组件(和子类)。它不会神奇地添加仅限于各种子类的关联,但如果需要,您可以添加一个单独的
base
关联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