问题
I've a User model embedding "one to many" Watchlists like the following :
class User
include Mongoid::Document
field :uid
field :name
field :user_hash
embeds_many :watchlists
end
class Watchlist
include Mongoid::Document
field :html_url
field :description
#field :name
field :fork_, :type => Boolean
field :forks, :type => Integer
field :watchers, :type => Integer
field :created_at, :type => DateTime
field :pushed_at, :type => DateTime
field :avatar_url
embedded_in :user
has_and_belongs_to_many :tags
end
The Watchlist should also references a many to many Tag model and vice versa :
class Tag
include Mongoid::Document
field :name, type: String
has_and_belongs_to_many :watchlists
end
Anyway, that's causing an error and seems that kind of "mixed" relation is not possible :
Mongoid::Errors::MixedRelations (Referencing a(n) Watchlist document from the Tag document via a relational association is not allowed since the Watchlist is embedded.):
app/controllers/home_controller.rb:53:in `tagging'
UPDATE Please note that watchlist, has to be dropped (user.watchlists.clear) than re-created (user.watchlists.find_or_create_by) four times a day, while Tag/s have to be persistent, relating the same embedded watchlists as before ( ... I'm not sure that is possible anyway, because of previous drop/creation ).
UPDATE of UPDATE ( tanks to durran support ) No, that's not possible: If you clear the embedded docs, the ids are gone as well, and new ones will get generate each time you create a new one.
Do you have any idea on how to overcome that ? Is it better to split all three models in referenced relations ( three different collections )?
回答1:
In mongoid you can't have references to embedded documents. So the problem is in your tag model defining habtm there. You can have HABTM in embedded watchlists, without any inverse relation.
class User
include Mongoid::Document
embeds_many :watchlists
end
class Watchlist
include Mongoid::Document
embedded_in :user
has_and_belongs_to_many :tags, inverse_of: nil
end
class Tag
include Mongoid::Document
end
But if you must have references to watchlists in tags, you can manually maintain array of ids on both sides as already pointed out by Tyler.
回答2:
Not the answer you are looking for but... for what it's worth, whenever I used HABTM relations in mongoid it either was buggy or didn't work. I don't know if this has been fixed but if you stick to just using arrays in the models and also on the reverse side of the relation you should be golden. Thats pretty much what the code would do for you anyway.
Yes, you have to do a bit more work to maintain the relationships but it actually works like it's supposed to.
Good luck.
来源:https://stackoverflow.com/questions/8437181/mongoiderrorsmixedrelations