开发者

Mongoid - One way references

Is it possible to do a one way reference in mongoid?

I would like to do something like:

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

and the blog model:

class Blog
  include Mongoid::Document
  include Mongoid::Timestamps

  belongs_to :editor, :class_name => "User", :inverse_of => :blogs

end

So, basically, I would like the User to store an object id r开发者_如何学运维eferencing the blog that it is currently editing/posting to. I do not need the blog to know about the active users, only the other way around.

It seems like the canonical way to do this would be to use 'belongs_to' on the User, and 'has_many' on the Blog. This does work, but it isn't ideal because it doesn't really semantically express the relationship between the two models.

I am new to Mongoid, and have not been able to find a better answer. Is there a better way to set up this type of releationship?

Thanks a ton!


If you do not even want to create even the accessor active_user on blog side, you can have:

class User
  belongs_to :active_blog, :class_name => "Blog", :inverse_of => nil
end

On the other hand has_many/has_one and belongs_to seems perfectly fine to me. It would not store user_ids in blog and blog doesn't need to know about active user unless you decide it should and start using the accessor from blog side.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜