0

我需要将评论链接到帖子。然而,评论可以是(用户生成的)简单文本、(系统生成的)链接或(系统生成的)图像。

起初,它们都具有相同的属性。所以我只需要创建一个类别属性,并根据该类别对文本属性做不同的事情。

例子:

class Comment < ActiveRecord::Base
  belongs_to :post
  belongs_to :author, :class_name => "User"

  CATEGORY_POST = "post"
  CATEGORY_IMAGE = "image"
  CATEGORY_LINK = "link"

  validates :text, :author, :category, :post, :presence => true
  validates_inclusion_of :category, :in => [CATEGORY_POST, CATEGORY_IMAGE, CATEGORY_LINK]

  attr_accessible :author, :text, :category, :post

  def is_post?
    self.category == CATEGORY_POST
  end

  def is_link?
    self.category == CATEGORY_LINK
  end

  def is_image?
    self.category == CATEGORY_IMAGE
  end

end

然而这现在还不够,因为我觉得将每个值都转储到通用“文本”属性中并不干净。所以我正在考虑创建一个多态模型(如果需要在工厂模式中)。但是当我在谷歌上搜索多态模型时,我得到的例子是对帖子的评论,但对页面的评论是相同的,这种关系。我对多态的理解是否不同(与在不同范围内行为相同的模型相比,模型在不同情况下的行为不同)?

那么我该如何建立这种关系呢?

我在想(请纠正我)

 Post
    id

 Comment
    id
    post_id
    category (a enum/string or integer)
    type_id (references either PostComment, LinkComment or ImageComment based on category)
    author_id

 PostComment
    id
    text

 LinkComment
    id
    link

 ImageComment
    id
    path

 User (aka Author)
    id
    name

但我不知道如何设置模型,以便我可以调用 post.comments(或 author.comments)来获取所有评论。一个不错的选择是评论的创建将通过评论而不是链接/图像/postcomment(评论充当工厂)

我的主要问题是,如何设置 activerecord 模型,使关系保持不变(作者有评论,帖子有评论。评论可以是链接、图片或帖子评论)

4

1 回答 1

1

我将只回答您的主要问题,模型设置。鉴于您在问题中使用的列和表格,除了评论,您可以使用以下设置。

 # comment.rb
 # change category to category_type
 # change type_id to category_id
 class Comment < ActiveRecord::Base
   belongs_to :category, polymorphic: true
   belongs_to :post
   belongs_to :author, class_name: 'User'
 end

 class PostComment < ActiveRecord::Base
   has_one :comment, as: :category
 end

 class LinkComment < ActiveRecord::Base
   has_one :comment, as: :category
 end

 class ImageComment < ActiveRecord::Base
   has_one :comment, as: :category
 end

使用该设置,您可以执行以下操作。

 >> post = Post.first
 >> comments = post.comments
 >> comments.each do |comment|
      case comment.category_type
      when 'ImageComment'
        puts comment.category.path
      when 'LinkComment'
        puts comment.category.link
      when 'PostComment'
        puts comment.category.text
      end
    end
于 2013-02-19T10:24:15.870 回答