Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 927
user545139 Avatar asked Feb 23 '23 14:02

user545139


1 Answers

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.

like image 133
moritz Avatar answered Mar 05 '23 16:03

moritz