是否可以在mongoid中进行单向引用?
我想做点什么:
class User
include Mongoid::Document
include Mongoid::Timestamps
has_many :blogs, :class_name => "Blog", :inverse_of => :editor
has_one :active_blog, :class_name => "Blog", :inverse_of => :active_users
end
和博客模型:
class Blog
include Mongoid::Document
include Mongoid::Timestamps
belongs_to :editor, :class_name => "User", :inverse_of => :blogs
end
所以,基本上,我希望用户存储引用当前正在编辑/发布到的博客的对象ID。我不需要博客了解活跃用户,只是反过来。
这样做的规范方法似乎是在User上使用'belongs_to',在Blog上使用'has_many'。这确实有效,但它并不理想,因为它并不真正在语义上表达两个模型之间的关系。
我是Mongoid的新手,但未能找到更好的答案。有没有更好的方法来建立这种类型的关系?
非常感谢!
答案 0 :(得分:5)
如果您甚至不想在博客端创建访问者active_user
,您可以:
class User
belongs_to :active_blog, :class_name => "Blog", :inverse_of => nil
end
另一方面,has_many / has_one和belongs_to对我来说似乎完全没问题。它不会在博客中存储user_ids,博客不需要知道活跃用户,除非你决定应该从博客那边开始使用访问者。