1

在将评论与用户和页面相关联时,我对belongs_toRails 中的关联感到困惑。我说的是有没有办法将评论与用户和页面相关联?采取以下(对我不起作用但演示的简单示例):

# The basic idea is that I would like to have User show comments from the user
# on all pages, and Page show all the comments for the page.
# User.find_by_email('email@domain.com').comments # Show comments on pages.
# Page.find_by_slug('my-slug').comments # Show comments on the page.

class Comments
  include Mongoid::Document and include Mongoid::Timestamps
  include MyApp::Mongoid::Patches::DefaultType

  belongs_to :page
  belongs_to :user

  field :content, type: String
end

class Page
  include Mongoid::Document and include Mongoid::Timestamps
  include MyApp::Mongoid::Patches::DefaultType

  belongs_to :user
  has_many :comments

  field :type, type: String, default: :post
  field :slug, type: String
  field :title, type: String
  field :content, type: String
  field :tags, type: Array, default: :user

  private
  # .....
end

class User
  include Mongoid::Document and include Mongoid::Timestamps
  include MyApp::Mongoid::Patches::DefaultType

  embeds_one :provider
  has_many :pages
  has_many :comments # But only from Pages not on the user.

  field :email, type: String
  field :name, type: String
  field :role, type: Symbol, default: :user
end
4

1 回答 1

0

听起来您在这里寻找的是多态关联。查看官方 Rails 多态关联指南的链接,但简而言之,您可以执行以下操作:

class Comments
  belongs_to :commentable, :polymorphic => true
end

class User
  has_many :comments, :as => :commentable
end

class Page
  has_many :comments, :as => :commentable
end

现在在评论表中添加两个字段 commentable_type(string) 和 commentable_id(integer)。

现在您的用户和页面都可以有评论。

如果comment 是一个Comment 对象,您可以使用comment.commentable 来获取该评论的用户/页面

于 2012-08-03T15:13:22.043 回答