Rails 和带有 has_many 的 STI 无法识别子类

发布于 2024-12-22 21:18:40 字数 599 浏览 5 评论 0原文

我有以下内容:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

仅此而已 2024-12-29 21:18:40

不,不应该。您已经说过 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文