在将评论与用户和页面相关联时,我对belongs_to
Rails 中的关联感到困惑。我说的是有没有办法将评论与用户和页面相关联?采取以下(对我不起作用但演示的简单示例):
# 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