在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。我不需要博客知道活跃的用户,只需要相反的方式。
似乎最规范的方法是在用户上使用“belongs_to”,在博客上使用“has_many”。这是可行的,但并不理想,因为它并没有真正在语义上表达两个模型之间的关系。
我是第一次接触Mongoid,还没有找到更好的答案。有没有更好的方法来建立这种关系?
非常感谢!
发布于 2011-08-12 18:00:23
如果你甚至不想在博客端创建访问器active_user,你可以拥有:
class User
belongs_to :active_blog, :class_name => "Blog", :inverse_of => nil
end另一方面,has_ me /has_one和belongs_to在我看来完全没问题。它不会在博客中存储user_ids,博客不需要知道活跃用户,除非你决定它应该知道,并从博客端开始使用访问器。
https://stackoverflow.com/questions/7008805
复制相似问题