是否可以在 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 新手,无法找到更好的答案。有没有更好的方法来建立这种类型的关系?
非常感谢!
最佳答案
如果您甚至不想在博客端创建访问器active_user
,您可以:
class User
belongs_to :active_blog, :class_name => "Blog", :inverse_of => nil
end
另一方面,has_many/has_one 和belongs_to 对我来说似乎完全没问题。它不会将 user_ids 存储在博客中,并且博客不需要了解事件用户,除非您决定应该了解并开始从博客端使用访问器。
关于Mongoid - 一种方式引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7008805/