Fran Martinez
Fran Martinez

Reputation: 3052

Scopes with Rails and Mongo

I have this 3 dependent models with Mongoid:

 class Account
   has_many :apps
 end

 class App
   belongs_to :account
   has_many :devices
 end

 class Device
   belongs_to :app
 end

I would like to get all the Device elements that belongs_to an Account, but the relation between Device and Account is through the model App.

In an ActiveRecord environment, it would be something like this:

scope :for_account, ->(account) { joins(:app).where("app.account = ?", account) }

How can I do this with Mongoid?

Upvotes: 0

Views: 479

Answers (1)

ThunderGuppy
ThunderGuppy

Reputation: 189

Two ways that I can think of to solve this.

Mongoid relations provide us with a pretty hefty set of methods to help us access objects.

For example:

app.account       #returns account object
app.account_id    #returns bson id of account object
account.apps      #returns collection of apps
account.app_ids   #returns array of app bson ids

We can use this so find all devices who's app ids are included in the list of app ids for an account. Something like:

Device.where(app_id: { '$in' => account.app_ids})

This will return a nice collection, just like any other mongo query, but has the drawback of searching the entire Device collection. Depending on your db size this might be a performance hit that you're not comfortable with.

Alternatively:

account.apps.collect{ |a| a.devices}.flatten

will provide an array of device items collected from all of the apps in an account.

This has the advantage of a more efficient search, and it is likely that the array will work fine for whatever you need this collection for.

Hope this helps!

Upvotes: 1

Related Questions