我有几个基本模型,Post
和Comment
,post
有很多comment
s:
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to: :post
end
我还在每个模型上都有单表继承,子类没有自己的数据库表。我在type
和posts
表中有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_comment
和comment
的数据相同,但行为略有不同。我希望ChildComment
仅覆盖Comment
的某些方法。我希望comment
和child_comment
成为可区分的数据库条目。
如果这里有更好的设计,我可以接受它。
答案 0 :(得分:0)
您需要在:class_name
关联中指定:foreign_key
和has_many
:
has_many :child_comments, class_name: "Comment", :foreign_key => "post_id"
:foreign_key
选项允许您直接设置外键的名称。因此,如果您将其设置为post_id
,那么它将起作用,因为post_id
表中存在comments
列。