In Mongoid how would I achieve the same thing that ActiveRecord :through =>
provides?
class Advertiser
include Mongoid::Document
embeds_many :campaigns
# how would I do this
embeds_many :advertisements, :through => :campaigns
end
class Campaign
embedded_in :advertiser
embeds_many :advertisements
end
class Advertisement
embedded_in :campaign
# or this?
embedded_in :advertiser, :through => :campaign
end
then be able to do
Advertiser.first.advertisements
and
Advertisement.first.advertiser
Advertiser.campaigns.collect{|campaign| campaign.advertisement}
is not an option
How, how would I do these with references_many
/ referenced_in
?
The short answer is that you can not. MongoDB does not have the concept of a join table nor does it do joins in general. The Mongoid many-to-many "simulation" is done by storing arrays of foreign keys on each side.
In response to a comment: MongoDB is a document store. It therefore suits situations where "documents" are highly heterogeneous. As you store your Advertisers with a subtree of Campains and Advertisements, you will have to collect the Advertisements for the Advertisers in ruby code. If your data has a very homogeneous form then you could consider using a relational database instead. We often used MySQL for relating objects and then added MongoDB documents to the objects so they would be extensible.
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