I want to store blog and its tags as separate documents.
Blog post should have tag_ids field and tag shouldn’t have blog_posts_ids field.
Mongoid provides many to many relations out of the box, but it requires both documents of many to many relation to have _ids field.
class BlogPost
include Mongoid::Document
field :title
references_many :tags, :stored_as => :array, :inverse_of => :blog_posts
end
class Tag
include Mongoid::Document
field :name
# I DON'T WANT TO STORE BLOG_POSTS_IDS IN TAG DOCUMENT
references_many :blog_posts, :stored_as => :array, :inverse_of => :tags
end
You can get around it with a method on
Tagto fake the other side of the associationObviously, this isn’t as full-featured as
:references_many, but you can similarly fake other aspects of the many-to-many relation. For example if you want the ability to assign a new blog_post to a tag you can add a simplecreate_blog_postmethod toTag.For many real-world situations, this kind of approach is practical as long as you keep the methods simple and don’t get carried away.