Rails:单表继承和在父级中查找(:all)

Ste*_*ell 3 ruby ruby-on-rails

我理解STI是如何工作的,因为我说的是Post模型,其中包含论坛上的帖子和几个子帖子,如'ordinaryUserPost'和'adminUserPost'等.

现在,我想在每个子帖子中定义相同的方法,但该方法会在每种情况下做一些不同的事情,例如

class Post < ActiveRecord::Base
end

class AdminUserPost < Post
  def background_color
    'rockstar red'
  end
end

class OrdinaryUserPost < Post
  def background_color
    'pale blue'
  end
end
Run Code Online (Sandbox Code Playgroud)

(是的,这是一个愚蠢的例子).现在在我的线程控制器中我做Post.find(:all)它给了我一个我需要渲染的帖子列表,但是它们是'Post'对象,而不是AdminUserPost或OrdinaryUserPost - 所以我不能只得到我的background_color方法!我必须分别对每种类型的用户帖子进行查找...

无论如何我能做到:

Post.find(:all)
Run Code Online (Sandbox Code Playgroud)

在结果数组中获取AdminUserPost和OrdinaryUserPost对象的列表而不是Post对象?

或者有一种很好的方法可以将我的Post对象"转换"为AdminUserPost和OrdinaryUserPost吗?

编辑:

这可以按预期工作 - 只要在Post类中有一个名为'type'的列.如果您的列被称为其他内容,例如'post_type',那么您需要添加:

self.inheritance_column = 'post_type'
Run Code Online (Sandbox Code Playgroud)

在所有子模型(本例中为AdminUserPost和OrdinaryUserPost)和父模型(Post)中.

谢谢,

斯蒂芬.

dst*_*rkr 7

仔细检查posts表是否有一个列'type'(字符串).如果将AdminUserPosts和OrdinaryUserPosts写入表'posts'并且type列正确,则应该获得所期望的子类行为.