user545139
user545139

Reputation: 935

Mongoid embeds / has_many :through equivalent

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?

Upvotes: 4

Views: 3217

Answers (1)

moritz
moritz

Reputation: 25757

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.

Upvotes: 8

Related Questions