rails has_many多个单表继承

时间:2015-08-15 19:43:45

标签: postgresql ruby-on-rails-4 has-many single-table-inheritance

我有几个基本模型,PostCommentpost有很多comment s:

class Post < ActiveRecord::Base
    has_many :comments
end

class Comment < ActiveRecord::Base
    belongs_to: :post
end

我还在每个模型上都有单表继承,子类没有自己的数据库表。我在typeposts表中有comments个列。

class ChildPost < Post
    has_many :child_comments, class_name: "Comment"
end

class ChildComment < Comment
    belongs_to :child_post, class_name: "ChildPost"
end

现在,如果我创建了一些这些对象

child_comment = ChildComment.create
child_post = ChildPost.create
child_post.child_comments << child_comment
child_post.save

当我child_post.child_comments时,我得到:

PG::UndefinedColumn: ERROR: column comments.child_post_id does not exist

child_post_id列不存在(它是post_id)是正确的,但我需要做些什么才能纠正这个问题?

在设计方面,我设置了这种方式,因为child_commentcomment的数据相同,但行为略有不同。我希望ChildComment仅覆盖Comment的某些方法。我希望commentchild_comment成为可区分的数据库条目。

如果这里有更好的设计,我可以接受它。

1 个答案:

答案 0 :(得分:0)

您需要在:class_name关联中指定:foreign_keyhas_many

has_many :child_comments, class_name: "Comment", :foreign_key => "post_id"

:foreign_key选项允许您直接设置外键的名称。因此,如果您将其设置为post_id,那么它将起作用,因为post_id表中存在comments列。