I have a few models that each have tags. Say for example, a User and a Post. Both should have embedded tags I think.
The user's embedded tags are their "favorites" and a post's tags are tags that have to do with the post.
I'm using Mongoid, and I can't figure out how to have a Tag model where I can find all the tags (These tags aren't embedded, I want a separate collection of all available tags).
When a user tries to add a tag, it is checked against Tag.all to make sure it exists. If it does, then it should be embedded in the User model.
I can't figure out how to embed Tag models in more than one model (User and Post) or how to embed Tag models as well as retrieve them like normal (I get the error: Access to the collection for Tag is not allowed since it is an embedded document, please access a collection from the root document.).
Ideas? Am I designing this totally wrong? I don't need complicated queries like "Retrieve all users who have the example tag", so I figured that I should embed to be more efficient.
Well, the first step is to make a tag a polymorphic embed.
class User
embeds_many :tags, :as => :taggable
end
class Post
embeds_many :tags, :as => :taggable
end
class Tag
embedded_in :taggable, :polymorphic => true
end
You could perhaps then have an instance of a user or a post that contains all tags available. And then instead of calling .all on the Tag class, you can call it on your instance
available_user = User.new
available_user.tags << Tag.new
available_user.tags.all
My solution is to have a Registry model that embeds_many tags, then to have an instance that has the registered tags that is checked before adding to a user or post. This is essentially the same as Ron's answer, but without overloading User.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With