Rails 3.2中的多个belongs_to

时间:2012-08-03 15:08:45

标签: ruby-on-rails ruby ruby-on-rails-3

当涉及将注释与用户和页面相关联时,我对Rails中的belongs_to关联感到困惑。我所说的是有一种方法可以将评论与用户和页面相关联吗?采取以下(简单的例子对我不起作用,但演示):

# 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

1 个答案:

答案 0 :(得分:0)

听起来你在这里寻找的是polymorphic association。查看官方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(整数)。

现在您的用户和网页都可以发表评论。

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